删除整个网站的“content”CSS属性“onclick”按钮

问题描述 投票:0回答:1

function myFunction() {
  document.getElementById('img');
  const element = document.styleSheets[0].cssRules[0].style.removeProperty('content');
}
img {
  content: url("https://static.vecteezy.com/system/resources/previews/005/476/277/original/under-18-forbidden-round-icon-sign-illustration-eighteen-or-older-persons-adult-content-18-plus-only-rating-isolated-on-white-background-free-vector.jpg");
  max-width: 100%;
  height: auto;
}
<button onclick="myFunction()">Show pics</button>

<img src="https://m.media-amazon.com/images/I/81K2hJBAduL.png">

重点是,点击“删除”按钮后,整个网站的“内容”属性。

javascript html css onclick
1个回答
2
投票

您真正需要的是在主体上设置一个类,这将影响页面上的每个图像:

function myFunction() {
  document.body.classList.add('permitted');
  setCookie('permitted-images', '1');
}

document.addEventListener('DOMContentLoaded', function(){
  if( getCookie('permitted-images') == '1' ){
    document.body.classList.add('permitted');
  }
});


/** functions for handling cookies **/
function setCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
body:not(.permitted) img {
  content: url("https://static.vecteezy.com/system/resources/previews/005/476/277/original/under-18-forbidden-round-icon-sign-illustration-eighteen-or-older-persons-adult-content-18-plus-only-rating-isolated-on-white-background-free-vector.jpg");
  max-width: 100%;
  height: auto;
}
<button onclick="myFunction()">Show pics</button>
<img src="https://m.media-amazon.com/images/I/81K2hJBAduL.png">

<img src="https://cdn.pixabay.com/photo/2023/04/02/12/40/mistletoe-7894574_1280.jpg">

<img src="https://cdn.pixabay.com/photo/2015/04/23/21/59/tree-736877_1280.jpg">

编辑:我添加了代码,使用 cookies 使该类在页面加载时保持不变。

注意:StackOverflow 上的代码片段中对 Cookie 进行了限制,因此此处测试时不起作用。不过我在本地测试过,确实有效。


cookie的默认过期时间是会话结束时;这意味着 cookie 将在网站关闭时被删除。要保留 cookie 更长时间,请在 setCookie 中添加天数:

setCookie('permitted-images', '1', 30);
(这将使 cookie 保留 30 天)。

在 javascript 中处理 cookie 的代码可在此处找到:stackoverflow.com/a/24103596/1678383

© www.soinside.com 2019 - 2024. All rights reserved.