简体   繁体   中英

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

  • my demo 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
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???)
// 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. 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?

From MDN Web Docs :

The style property is used to get as well as set the inline style of an element.

Hence, the style property would not work with embedded or external 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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