我想在用戶點擊一個按鈕時修改頁面的CSS(隱藏某個類的元素,「class」)。我似乎無法找到正確的JavaScript來獲取此按鈕來觸發樣式更改。我寧願避免在我的解決方案中使用jQuery。更改HTML按鈕點擊CSS?
HTML:
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css" />
<script type="text/javascript" src="content.js"></script>
</head>
<body>
<p>hide "class"</p>
<button type="button" onclick="hide_class()">hide class</button>
</body>
</html>
的JavaScript:
function hide_class() {
document.addEventListener("DOMSubtreeModified", function (event) {
if (document.getElementsByClassName(".class")) {
var x = document.querySelectorAll(".class");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.visibility = "hidden";
}
}
});
}
編輯:這是我的manifest.json 和background.js
manifest.json的(沒有引用content.js):
{
"manifest_version": 2,
"name": "my extension",
"description": "it doesnt work",
"version": "0.1",
"background": {
"scripts": ["background.js"],
"persistent": false
},
"permissions": [
"declarativeContent"
],
"page_action": {
"default_popup": "popup.html"
},
"icons" : { "16": "16.png",
"48": "48.png",
"128": "128.png" },
}
Background.js:
chrome.runtime.onInstalled.addListener(function() {
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
chrome.declarativeContent.onPageChanged.addRules([
{
conditions: [
new chrome.declarativeContent.PageStateMatcher({
pageUrl: { urlContains: 'g' }, //url contains g
})
],
actions: [ new chrome.declarativeContent.ShowPageAction() ]
}
]);
});
});
你想添加監聽或改變風格? –
我想在點擊按鈕時改變樣式,但我相信我需要實現監聽器來改變樣式,除非有人對如何實現這一點有更好的想法。 – Nat
偵聽器偵聽到更改,但不會啓動更改 –