基于JavaScript变量动态添加和删除样式

时间:2014-06-07 18:11:57

标签: javascript

我正在使用JavaScript动态生成div。当鼠标悬停在页面中的某些元素上时,会出现新的div。在mouseout上它消失了。一切正常。但我希望div根据鼠标所在的元素位于顶部。所以我用getBoundingClientReach

记录元素的位置
function lopen(AbstId) {  //called OnMouseOver
    var rect = document.getElementById(AbstId).getBoundingClientRect();
    var st3="px";
    divtop = rect.top+st3 ;
    alert ("Hello :" + divtop);  //for checking purposes only

    if (this.element == null) {
        this.element = document.createElement('div');
        this.element.id = "myPopup";
        this.element.className = "myPopupBody";
        this.element.onmouseover = 'prevent()';  //if mouse over new div, do not close  
        this.element.style["top"] = divtop;   //HERE IS MY PROBLEM
    }

    document.body.appendChild(this.element);
    popUpDetails();
}

function lclose () {  //called OnMouseOut
    document.getElementById("myPopup").innerHTML = " "; 
    document.body.removeChild(this.element);
}  

这段代码

this.element.style["top"] = divtop;

在第一个事件中获得了正确的最高值,但是没有实现进一步的onmouseover事件,即使divtop实际上正在刷新(我查看了第5行的警报)。 有人发现了这个问题吗?

1 个答案:

答案 0 :(得分:0)

同样,只是为了完整性。问题是样式分配错误:top。在正确的代码下面

function lopen(AbstId) {  //called OnMouseOver
    var rect = document.getElementById(AbstId).getBoundingClientRect();
    var st3="px";
    divtop = rect.top+st3 ;
    //alert ("Hello :" + divtop);  //for checking purposes only

    if (this.element == null) {
        this.element = document.createElement('div');
        this.element.id = "myPopup";
        this.element.className = "myPopupBody";
        this.element.onmouseover = 'prevent()';  //if mouse over new div, do not close  
        //this.element.style["top"] = divtop;   //here WAS my problem -deleted line
    }

    document.body.appendChild(this.element);
    document.getElementById("myPopup").style["top"] = divtop;  //here right code
    popUpDetails();
    }