简体   繁体   English

jQuery如果div位于x位置,则显示另一个div

[英]jQuery if div is in x position, then reveal another div

I have a div that is moveable in all directions with the keyboard arrows. 我有一个div,可使用键盘箭头在所有方向上移动。

I'm trying to make it so that when the moveable div 'walks' down the page and reaches a certain point, another div with text in it appears. 我试图做到这一点,以便当可移动div在页面中“行进”并到达某个点时,将出现另一个带有文本的div。

How do I make it so that when the character reaches a certain point on the page, a div dialogue shows? 如何使角色到达页面上的某个点时显示div对话框?

if($('#'+character).position().top > -500) {

    if(character == 'character1') {
       $('#page2 .dialogue').fadeIn(4000);

    }
}

So position () is relative to the containing element while offset() is relative to the document. 因此, position ()相对于包含元素,而offset()相对于文档。 With that said, you are asking when an element is 500 above the containing div. 这么说,您要问的是元素何时位于包含div的上方 500。 You may not be able to see it. 您可能看不到它。 Try removing the negative sign. 尝试消除号。

If you provide a jsfiddle then we can confirm and provide better help. 如果您提供jsfiddle,那么我们可以确认并提供更好的帮助。

In CSS, you can set element.style.top but you cannot read it. 在CSS中,您可以设置element.style.top,但无法阅读。 You need to use element.offsetTop instead, which will give you the position of your div. 您需要改为使用element.offsetTop,这将为您提供div的位置。 I'll assume character is a variable which has been defined in advance and is the ID of the div layer. 我假设character是一个预先定义的变量,它是div层的ID。

if(document.getElementById(character).offsetTop > 500) {

    if(character == 'character1') {
       $('#page2 .dialogue').fadeIn(4000);

    }
}

Oughta do the trick. Oughta做到了。 Call it occasionally to keep checking. 偶尔调用它以继续检查。 Or even better yet, don't bother with any of that. 甚至更好的是,不要理会任何一个。 Keep the character's position in a variable, then set their position that way, and when you need to read the coordinates of the character just read the variable. 将角色的位置保留在变量中,然后以这种方式设置其位置,当您需要读取角色的坐标时,只需读取变量即可。 That's how I'd approach it. 这就是我要采取的方法。

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

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