change some css property in a wordpress theme using jquery

时间:2015-07-13 21:02:13

标签: javascript jquery wordpress

I want to create one(or two) button(s) to switch my theme from dark to bright, i didn't know anything about jquery but I read something in w3schools and other references so I wrote a Jquery function that change some properties in my css file:

<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p").css({
            "color": "white",

        });
        $("div").css({
"background-color" : "black",});
    });
});

</script>

I put this script in bottom of header tag in header.php file, and I add a button to the footer of site

<button class="bright">طرح روشن</button>

but when I click on the button nothings happen, when I try this code on w3shcools editor it works but the button in my wordpress site does nothing. here is my code in W3shcools editor:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p").css({
            "color": "white",
            "background-color": "#98bf21",
            "font-family": "Arial",
            "font-size": "20px",
            "padding": "5px"
        });
    });
});
</script>
</head>
<body>

<button>Set multiple CSS properties for all p elements</button>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

</body>
</html>

And if there is a way to call that function with "href" I will grateful to help me how can I call it.

3 个答案:

答案 0 :(得分:1)

You need to include the jQuery library on your page. You are using jQuery correctly but jQuery was not included on your page. Add the script like this.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

答案 1 :(得分:1)

You have a syntax error, try this,

<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p").css({
            "color": "white" 
        });
        $("div").css({
        "background-color" : "black"});
    });
});

</script>

You had a , after "background-color" : "black" and "color": "white"

And yeah, do add jQuery library, if you haven't like this,

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

答案 2 :(得分:0)

最好的方法是addClass()

将你的css放入css文件中的一个类:

.my-style {
    /* add your styles here */
}

然后使用addClass()将css类添加到JQuery中的元素:

$('.my-element').addClass('my-style');

这使您的样式与JQuery分离,这是一种更好的工作方式,因为它使样式可重用,并在功能(JQuery和JavaSCript)和样式(css)之间实现更好的分离。您现在不必去两个地方更改颜色,如果您想在其他地方添加样式,您只需使用该类即可。

它也使得更简洁,更易理解的JQuery。

您也可以使用removeCLass()执行相反的操作。