Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在内容之后切换CSS_Javascript_Css - Fatal编程技术网

Javascript 在内容之后切换CSS

Javascript 在内容之后切换CSS,javascript,css,Javascript,Css,每次单击链接时,我都试图将:在属性之后从+切换到-,或者反之亦然 我有下面的javascript、css和html,但是当再次单击链接时,它只会将+变成-,而不会再返回 $(“#标题1”)。单击(函数(){ document.querySelectorAll('#heading1')[0].style.setProperty(“--content”,“'-”); } #标题1:之后{ 内容:var(--content,“+”; } link使用getPropertyValue(“--conte

每次单击链接时,我都试图将
:在
属性之后从+切换到-,或者反之亦然

我有下面的javascript、css和html,但是当再次单击链接时,它只会将+变成-,而不会再返回

$(“#标题1”)。单击(函数(){
document.querySelectorAll('#heading1')[0].style.setProperty(“--content”,“'-”);
}
#标题1:之后{
内容:var(--content,“+”;
}
link
使用
getPropertyValue(“--content”)
获取当前值,如果为空,则返回破折号,如果为破折号,则清空值,并使用变量的默认值

$(“#标题1”)。单击(函数(){
const content=this.style.getPropertyValue(“--content”);
this.style.setProperty(“--content”,content==”?“-”:”);
})
#标题1:之后{
内容:var(--content,“+”;
}


链接
这应该可以做到:

$('#heading1').click(() => {

    // Get the current value
    let value = this.style.getPropertyValue('--content');

    // Invert the value
    value = value === '+' ? '-' : '+';

    // Set the value
    this.style.setProperty('--content', value);

});
此外,我注意到您正在使用
document.querySelectorAll(“#heading1”)
。关于这一点,需要注意两件事:

  • 因为您正在引用当前元素,所以只需使用
    this
  • 如果确实需要获取元素(不包括使用jQuery的事实),可以使用
    document.getElementById
    ,因为“#heading1”是一个id

我喜欢您的恢复为默认值的方式,而不是“+”。聪明:-)+1谢谢-还有信息!