繁体   English   中英

使用按钮更改Wordpress中的背景颜色

[英]Changing background color in wordpress with a button

我目前正在尝试在WordPress上设计一个页面,该页面中我想实现一个夜间模式。

基本上,当您按下按钮(图像)时,背景颜色将从白色变为黑色(后来也变为文本颜色)。

由于WordPress,我必须使用inline-css和JavaScript。 现在,我正在尝试以下代码:

<script type="text/javascript">
var activated = 0; 
function changeBgCol() 
{ 
    if (activated == 0) 
    { 
         document.body.style.backgroundColor = "black"; 
         document.body.style.color = "white"; 
         activated = 1; 
     } 
     else 
     {  
         document.body.style.backgroundColor = "white"; 
         document.body.style.color = "black"; 
         activated = 0; 
     } 
}
</script>

和按钮(图像):

<a><img class="alignnone size-medium wp-image-2591" onclick="javascript:changeBgColor()" src="https://www.[WEBSITE].se/main/wp-content/uploads/2013/11/[PICTURE]-300x300.png"  width="480" height="480" /></a>

但是,当我对其进行测试时,该图像不可单击,并且背景颜色不会改变。

可能是什么问题?

最好的祝福

最好的方法是在身体上切换一个类。

$('.yourbutton').on('click', function(){
    $('body').toggleClass('theme--dark');
});

然后只需添加相应的CSS。

.theme--dark {
    background-color: #111;
}

您已将onClick事件设置为changeBgColor,并将JavaScript中的函数设置为changeBgCol。 每当遇到使脚本无法正常工作的问题时,请始终检查开发人员控制台。 尝试这个:

<a><img class="alignnone size-medium wp-image-2591" onclick="javascript:changeBgCol()" src="https://www.[WEBSITE].se/main/wp-content/uploads/2013/11/[PICTURE]-300x300.png"  width="480" height="480" /></a>

<script>
    var activated = 0;

    function changeBgCol() {
        if (activated == 0) {
            document.body.style.backgroundColor = "black";
            document.body.style.color = "white";
            activated = 1;
        } else {
            document.body.style.backgroundColor = "white";
            document.body.style.color = "black";
            activated = 0;
        }
    }
</script>

通常,使用内联脚本不是最佳实践。 您可能想要尝试这样的方法,而不是继续: https : //jsfiddle.net/eL46ch5y/或使用jQuery

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM