日期:2014-05-16  浏览次数:20305 次

在javascript中if语句判断失误是怎么回事?
<style type="text/css">
#touxiang{ width:360px; height:360px; margin:100px auto; border:1px solid #999; background-color:#fbfbfb;}
img{ height:100%; width:100%;}
</style>
<script type="text/javascript">
window.onload=startqiehuan;
function startqiehuan(){
document.onmousemove=qiehuan;
}
function qiehuan(){
var imgs=document.getElementsByTagName("img");
var touxiang=document.getElementById("touxiang")
var x=window.event.clientX;
var y=window.event.clientY;
var left=touxiang.offsetLeft;
var top=touxiang.offsetTop;
var width=touxiang.offsetWidth;
var height=touxiang.offsetHeight;
var righttop=touxiang.offsetLeft+touxiang.offsetWidth;
document.getElementById("zuobiao").value=x+":"+y+"和"+left+":"+top;
if(x<touxiang.offsetLeft&&y<touxiang.offsetTop){
alert("左上");
}else
if(touxiang.offsetLeft<x<touxiang.offsetWidth+touxiang.offsetLeft&&y<touxiang.offsetTop){
alert("上方");
}}
</script>
</head>

<body>
<div id="touxiang">
<input type="text" id="zuobiao"/>
<img src="png-0001.png" />
<img src="png-0002.png" style=" display:none" />
<img src="png-0003.png" style=" display:none"/>
<img src="png-0004.png" style=" display:none"/>
<img src="png-0005.png" style=" display:none"/>
<img src="png-0006.png" style=" display:none"/>
<img src="png-0007.png" style=" display:none"/>
<img src="png-0008.png" style=" display:none"/>
<img src="png-0009.png" style=" display:none"/>
<img src="png-00010.png" style=" display:none"/>
</div>
</body>
</html>
在上面的代码中,我认为红色部分是出错的地方但是,有不知道是怎么错了,而且并未报错!当鼠标移动的坐标并不满足if的判断条件依然执行了alert("上方")。更确切的说是说x的坐标已经超过了touxiang.offsetWidth+touxiang.offsetLeft的范围依然执行。很费解!希望高手指教。

------解决方案--------------------
if(x<s<y) 语法上是通的过的,
相当于 if( (x<s) < y )

如果x<s 为true, 则相当于 if( true < y ), 相当于 if( 1 < y )
如果x<s 为false,则相当于 if( false < y ), 相当于 if( 0 < y )

楼主明白为什么判断失效了吧