gpt4 book ai didi

javascript - 单击 HTML 按钮更改 CSS?

转载 作者:行者123 更新时间:2023-11-28 04:36:00 26 4
gpt4 key购买 nike

我想在用户单击按钮时修改页面的 CSS(隐藏某个类的元素,“类”)。我似乎无法找到正确的 JavaScript 来让这个按钮触发样式更改。我宁愿在我的解决方案中避免使用 jQuery。

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.jsonbackground.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" },

}

背景.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() ]
}
]);
});
});

最佳答案

您可以向该元素添加一个事件监听器。

示例:

HTML

<div id="hide_me">
I will hide if you click me
</div>

JS

document.getElementById('hide_me').addEventListener('click', function () {
this.style.display = 'none';
});

fiddle :https://jsfiddle.net/y1gc01zj/1

编辑您还可以添加一个 css 类:

CSS

.hide {
display: none;
}

JS

document.getElementById('hide_me').addEventListener('click', function () {
// this.style.display = 'none';
this.classList.add('hide')
});

关于javascript - 单击 HTML 按钮更改 CSS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41473093/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com