简体   繁体   中英

Javascript: How do I check a css style and then change another css style?

I'm trying to check if the left css property of a div named #right is equal to 0% and then if this equals true then change the display property of another div named #menu to 'none' .

I know to get a CSS style you use the following function:

document.getElementById("right").style.left = '0%'

But I can't work out how to always run this function so that as soon as the left style equals 0% , then hide the menu div.

I have tried numerous ways of doing this and can't seem to get it to work. Perhaps there is a better way of achieving this.

Any help would be greatly appreciated. Thanks!

Step 1 : create a function

function setMenuDisplay() {
  var right = document.getElementById("right");
  var menu = document.getElementById("menu");
  menu.style.display = right.offsetLeft ? "block" : "none";
}

Step 2 : Call this function in any event that can change the #right property left (window.onload, window.onresize or any function affecting the contents of the page)

To think wider just use getComputedStyle() function. It returns strings with CSS property value of element:

console.log(getComputedStyle(someElement).opacity) //0.5
console.log(getComputedStyle(someElement).width) //47px
//and on, and on…

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