最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Change CSS on HTML button click? - Stack Overflow

programmeradmin1浏览0评论

I want to modify the CSS of a page (hide elements of a certain class, "class") when a user clicks a button. I can't seem to find the correct JavaScript for getting this button to trigger the style change. I would prefer to avoid jQuery in my solution.

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";
            }
        }
    });
}

Edit: Here is my manifest.json and background.js

Manifest.json (does not reference 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() ]
  }
 ]);
 });
 });

I want to modify the CSS of a page (hide elements of a certain class, "class") when a user clicks a button. I can't seem to find the correct JavaScript for getting this button to trigger the style change. I would prefer to avoid jQuery in my solution.

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";
            }
        }
    });
}

Edit: Here is my manifest.json and background.js

Manifest.json (does not reference 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() ]
  }
 ]);
 });
 });
Share Improve this question edited Jan 8, 2017 at 4:41 Nat asked Jan 4, 2017 at 20:56 NatNat 671 silver badge10 bronze badges 5
  • do you want to add listener or change style? – Iłya Bursov Commented Jan 4, 2017 at 21:08
  • I want to change the style when the button is clicked, but I believe I need to implement the listener to change the style, unless someone has a better idea on how to acplish this. – Nat Commented Jan 4, 2017 at 21:12
  • listener listens to changes, it does not initiates changes – Iłya Bursov Commented Jan 4, 2017 at 21:38
  • Your "wondering" regarding your Chrome extension can not be addressed without more code (i.e. a plete minimal reproducible example that includes your manifest.json and any background script). However, your content script does have to get injected into the page somehow. There are two ways to do so, either a content_script entry in manifest.json or using chrome.tabs.executeScript() in your background script/popup. – Makyen Commented Jan 4, 2017 at 21:42
  • I was not sure if more code was necessary but I've updated it for the sake of clarity – Nat Commented Jan 4, 2017 at 22:13
Add a ment  | 

3 Answers 3

Reset to default 2

You could add an event listener to the element.

Example:

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/y1gc01zj/1

EDIT you could also add a css class:

CSS

.hide {
  display: none;
}

JS

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

Probably you're looking for this:

function sw(cl, v) {
  var a = document.getElementsByClassName(cl);
  for (var i=0; i<a.length; i++) a[i].style.visibility = v;
}
<p class="c1">c1</p>
<p class="c2">c2</p>
<p class="c1">c1</p>

<button onclick="sw('c1', '');">show c1</button>
<button onclick="sw('c1', 'hidden');">hide c1</button>

<button onclick="sw('c2', '');">show c2</button>
<button onclick="sw('c2', 'hidden');">hide c2</button>

Your issue is this typo:

in function hide_class() {

if(document.getElementsByClassName(".class")) {

should be

if(document.getElementsByClassName("class")) {

发布评论

评论列表(0)

  1. 暂无评论