简体   繁体   English

如何在具有绝对位置的元素旁边定位div?

[英]How to position a div next to element with absolute position?

I am trying to create a div that can be attached to an element whenever user hover to the link 我试图创建一个div ,可以在用户悬停到链接时附加到元素

I have many links and my codes look like the following. 我有很多链接,我的代码如下所示。

for loops to create many links for loops创建许多链接

codes....

link.href='#';
link.innerHTML = 'test'
link.onmouseover = OnHover;

codes....


function OnHover(){
    var position;
    var div = document.createElement('div');
        div.className='testdiv';
        div.innerHTML = 'test';

        position=$(div).position();

        div.style.top = position['top'] + 15 + 'px';
        $(this).prepend(div);
}


    link element1
    link element2
 ----
|    |   //add new div when hover link element2
 ----
    link element2
    link element3



my css

.testdiv{
    position:absolute;
}

I want to add a new div everytime the user hover to my link and position on the left top of the element. 每当用户将鼠标悬停在链接上并且位于元素left top位置时,我想添加一个新的div

My code would position all the div on top instead of every element. 我的代码将所有div放在顶部而不是每个元素。

Are there anyway to do this? 反正有吗? Thanks so much! 非常感谢!

Without seeing your other JavaScript/markup I can make the following observations: 在没有看到您的其他JavaScript /标记的情况下,我可以进行以下观察:

  • You need to set position:absolute on your new div before top will do anything. 您需要设置position:absolute在你的新divtop会做任何事情。
  • You need to make sure link is non- position:static . 您需要确保link是非position:static
  • Non-dynamic styles like the above should be in your CSS, not JS. 像上面这样的非动态样式应该在你的CSS中,而不是JS。
  • Positioning absolutely means you shouldn't need to use $(div).position() 绝对定位意味着您不需要使用$(div).position()
  • You're using a mix of jQuery and pure JavaScript which looks a little odd :) 你正在使用混合的jQuery和纯JavaScript,看起来有点奇怪:)

JS JS

function OnHover() {
    var position;
    var div = $('<div></div>');
    div.addClass('testdiv');
    div.html('test');
    div.css('top', 15);
    $(this).prepend(div);
}

CSS CSS

.testdiv {
    position:absolute;
}

a.testanchor {
    position:relative;
}

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

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