开发者

Dropdown menu positioning with jquery

开发者 https://www.devze.com 2023-03-19 08:43 出处:网络
I am trying to create a dropdown menu and i need to detect the corect position for the submenu. This is how i indent it with jquery:

I am trying to create a dropdown menu and i need to detect the corect position for the submenu. This is how i indent it with jquery:

function changeSubcat(catid){
    var position = $('#menuparent_'+catid).position();
    position.left = position.left - 18开发者_Go百科0;
    $('#menu_'+catid).css("left", position.left);
}

The real problem is that it works just for a window of the size i worked on, obviosly, so i need to optimize it to work on other dimensions. First i thought i should use another method than position() , but i haven't found a better one. Sorry for not providing the html code but it is a little furry.


I don't understand why do you use margin left and left at the same time to position the element. Using only

function changeSubcat(catid) {
    var position = $('#menuparent_'+catid).position();
    // maybe add a little something to position.top to make the menus not overlap
    $('#menu_'+catid).position(position);
}

should work. At times I find that position() does not work, and instead you can also try offset(). And in some rare cases I have also had problem with both position() and offset() in which case you can use $('#menuparent_'+catid)[0].offsetTop and $('#menuparent_'+catid)[0].offsetLeft to get and set the position.

Edit: And by the way, you don't have to parse the position.left or right since they are already integers.


As far as I can see you just want to positon the dropped element. Why do you use JS for this at all? Would not the pure CSS solution Solve your issue?

0

精彩评论

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