开发者

How to tell if one Div is to the right or left of another div? Jquery Javascript

Say that you have this:

<div i开发者_开发知识库d="1"></div><div id="2"></div><div id="3"></div>

Can you use Javascript/jQuery to find that id="2" is to the right of id="1"?


if you're looking for the div that comes before #2, do something like this:

$("#2").prev("div")


I'm not an expert, but no, i don't think you can.

First off are you talking about in the code or how it comes out on the screen? 3 divs listed like will actually each show up on thier own lines. You need to use spans to keep them all on the same line.


Yes. How you check that depends on what you mean exactly by "to the right".

You can use the offset method to get the position of the two elements:

o1 = $('#1').offset();
o2 = $('#2').offset();

Now you can compare the left and top properties of the o1 and o2 objects.

If you by "to the right" mean that they are beside each other, and the second div is on the right side, you have to compare both properties:

if (o1.top == o2.top && o1.left < o2.left) ...

If you only mean that the second div should be more to the right than the first, then you only need to compare the left properties:

if (o1.left < o2.left) ...

Note that an id should not start with a digit. Using for example id="x1" and id="x2" would be valid.


I'd do something like:

function is_div2_after_div1() {
  is_after = null;
  $("#parent > div").each(function(i, el) {
    if (is_after !== null) return;
    if (el.id && el.id == "div1") is_after = true;
    if (el.id && el.id == "div2") is_after = false;
  }
  return is_after;
}


You could get their positions, and if div#i1's position is lesser than the one of div#i2's position (their x positioning, if you will). http://api.jquery.com/position/

#Requires jQuery
var d1x = $('div#i1').position().left,
    d2x = $('div#i2').position().left;

$('span').html((d1x < d2x) ? "yes" : "no");

I don't think IDs can be solely numeric. It might work, but it's not a good practice.

jsFiddle: http://jsfiddle.net/PKpdp/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜