简体   繁体   English

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

[英]Changing background color in wordpress with a button

I'm currently trying to design a page on WordPress in which I would like to implement a night-mode. 我目前正在尝试在WordPress上设计一个页面,该页面中我想实现一个夜间模式。

Basically, when you press a button(image), the background color will change from white to black (later on, also the text color). 基本上,当您按下按钮(图像)时,背景颜色将从白色变为黑色(后来也变为文本颜色)。

I have to use inline-css and JavaScript because of WordPress. 由于WordPress,我必须使用inline-css和JavaScript。 Right now, I am trying this code: 现在,我正在尝试以下代码:

<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>

and the button(image): 和按钮(图像):

<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>

But when I test, it, the image is not clickable and the background color doesnt change. 但是,当我对其进行测试时,该图像不可单击,并且背景颜色不会改变。

What could be the issue? 可能是什么问题?

Best regards 最好的祝福

The best way is to toggle a class on the body. 最好的方法是在身体上切换一个类。

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

Then just add the corresponding CSS. 然后只需添加相应的CSS。

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

You had the onClick event set to changeBgColor, and the function in the JavaScript set to changeBgCol. 您已将onClick事件设置为changeBgColor,并将JavaScript中的函数设置为changeBgCol。 Always check your developer console whenever you run into problems getting a script to work. 每当遇到使脚本无法正常工作的问题时,请始终检查开发人员控制台。 Try this: 尝试这个:

<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>

It's not generally considered best practice to use inline scripts. 通常,使用内联脚本不是最佳实践。 You might want to try something like this instead going forward: https://jsfiddle.net/eL46ch5y/ or use jQuery . 您可能想要尝试这样的方法,而不是继续: https : //jsfiddle.net/eL46ch5y/或使用jQuery

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

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