简体   繁体   中英

“if” statement parameters not functioning as intended. JavaScript

The following JavaScript "if" statement is not reading the parameters as I intended both parameters to be read. When I shoot bulletOne with a function that uses an interval to run bulletOneLeft++; the left CSS property of bulletOne increases by 1 with each interval as intended. However, when I coded the following if statement to detect the CSS style.left property of the bulletOne and compare it to the CSS style.left property of an element called " targetBox "; the code does not recognize the difference of the CSS style.left properties of these two elements. My question is how can I make this if statement execute once bulletOne's CSS style.left property is greater than targetBox's CSS style.left property numerically?

if (bulletOneLeft > targetLeftProp){
document.getElementById("targetBox").style.opacity = "0";   
};

The two parameters of bulletOneLeft and targetLeftProp are described with the following code;

bulletOneLeft;

#bulletOne {
position: absolute;
background-color: white;
height: 1px;
width: 6px;
top: 0px;
left: 0px;
}
bulletOne.style.left = bulletOneLeft;

targetLeftProp;

#targetBox{
position: absolute;
background-color: green;
height: 20px;
width: 20px;
top: 30px;
left: 310px;
opacity: 1;
}
var targetLeftProp = window.getComputedStyle(CSSelement, 
null).getPropertyValue("left");

PREVIOUS FAILED ATTEMPT; I have tried many different combinations of code, the following was my first failed attempt. The following code seemed the most logical at the time;

var bulletLeft = document.getElementById("bulletOne").style.left;
var targetLeft = document.getElementById("targetBox").style.left;

if (bulletOneLeft > targetLeft){
   document.getElementById("targetBox").style.opacity = "0";   
};

So first of all you made a typo that is why it doesnt work in your failed attemps.

Your variable is named bulletOne but you do your if statement with bulletOneLeft .

Also :

style.left;

return a string, so you have to do use parseFloat function or parseInt if you're sure it will always be an int ( https://www.w3schools.com/jsref/jsref_parsefloat.asp , https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt ) as following :

var bulletOne = parseFloat(document.getElementById("bulletOne").style.left;

And you are good to go I believe.

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