简体   繁体   中英

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.

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.

How do I make it so that when the character reaches a certain point on the page, a div dialogue shows?

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. With that said, you are asking when an element is 500 above the containing div. 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.

In CSS, you can set element.style.top but you cannot read it. You need to use element.offsetTop instead, which will give you the position of your div. I'll assume character is a variable which has been defined in advance and is the ID of the div layer.

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

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

    }
}

Oughta do the trick. 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.

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