简体   繁体   English

用js成功扭转了过渡,但为什么我的另一种方式不起作用?

[英]successfully reverse the transition with js ,but why my another way doesn't work?

  • my demo jsfiddle我的演示jsfiddle
  • What I want is a reverse transition when I click the < li > again, but the commentted code didn`t work,and the code below works fine我想要的是当我再次单击 <li> 时的反向过渡,但注释代码不起作用,下面的代码工作正常
let dbclickre = true;
function flipped() {
    if (dbclickre) {
        document.querySelector(".linkrec").setAttribute("Id", "flipped");
    } else {
        document.querySelector(".linkrec").removeAttribute("Id", "flipped")
    }
    dbclickre = !dbclickre;
}
  • below is the commentted code (I think when i firstly click the last < li >,js will excute the if statement(and indeed it works fine),but when i click again, the else statement didn't excude(but i have set #flipped.reverse {background: whitesmoke} ). why this happening???)下面是注释代码(我认为当我第一次单击最后一个 <li> 时,js 将执行 if 语句(确实它工作正常),但是当我再次单击时,else 语句没有排除(但我已经设置#flipped.reverse {背景:whitesmoke})。为什么会这样???)
// const dbclickre = document.querySelector(".reverse");
// function flipped() {
//     if (dbclickre.style.backgroundColor = 'white') {
//         document.querySelector(".linkrec").setAttribute("Id", "flipped");
//     } else {
//         document.querySelector(".linkrec").removeAttribute("Id", "flipped")
//     }
// }

Instead of relying on background color for checking the state of flip, you could check for existence of Id attribute.您可以检查是否存在Id属性,而不是依赖背景颜色来检查翻转的 state。 Here the the changed code:这里是更改后的代码:

const dbclickre = document.querySelector(".reverse");
function flipped() {
    if ( document.querySelector(".linkrec").getAttribute("Id") == undefined ) {
        document.querySelector(".linkrec").setAttribute("Id", "flipped");
    } else {
        document.querySelector(".linkrec").removeAttribute("Id", "flipped")
    }
}

Edit:编辑:

Why element.style would not work?为什么element.style不起作用?

From MDN Web Docs :来自MDN Web 文档

The style property is used to get as well as set the inline style of an element. style属性用于获取和设置元素的内联样式。

Hence, the style property would not work with embedded or external CSS.因此, style属性不适用于嵌入式或外部 CSS。

Also, it may not be a good idea to use hard-coded colors as the condition, because changing colors in the respective CSS classes would completely break the functionality.此外,使用硬编码的 colors 作为条件可能不是一个好主意,因为在相应的 CSS 类中更改 colors 会完全破坏功能。

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

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