如何解决 - DIV元素在渲染后立即闪烁/消失

时间:2009-11-30 11:32:36

标签: javascript javascript-events

这是正在发生的事情

  • 页面加载后,javascript从底层代码中读取XML
  • XML包含一堆字段ID,当鼠标悬停在列出的字段ID上时,弹出窗口中会显示相应的内容

我的代码生成一堆弹出窗口作为带有样式

的div元素
.render{
 background-color:    #fffc80;
 border:             .1em solid rgb(200, 128, 0);
 padding-left:        2px;
 padding-right:       2px;
 z-index:             1000;
}

.hide{
 display:none;
}

所有创建的弹出窗口都附加到根元素。

已编辑:已添加脚本摘要

事件处理程序如下所示

// instantiate a div element

var myDiv = document.createElement('div');

// generate an ID 

myDiv.id = generatePopupId(getFieldId());

// attach the content from the XML into the new div element

myDiv.innerHTML = getPopupContent();

// apply mouseover/out handlers to the main element

document.getElementById(getFieldId()).onmouseover = function(){
  showPopup(generatePopupId(getFieldId()));
};

document.getElementById(getFieldId()).onmouseout = function(){
  hidePopup(generatePopupId(getFieldId()));
}; 


// read the X coordinate of the present position of the mouse

function getX(){
  var e = window.event;
  posX = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
  return posX;
}

// read the Y coordinate of the present position of the mouse

function getY(){
  var e = window.event;
  posY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
  return posY;
}

// Show the popup element at the current mouse location

function showPopup(popupId){
  var posX = getX();
  var posY = getY();

  var poppyElement = document.getElementById(popupId);

  poppyElement.className = 'render';
  poppyElement.style.left = posX;
  poppyElement.style.top  = poxY;
  poppyElement.style.position = 'absolute';
  poppyElement.style.display = '';

}

// hide the popup element

function hidePopup(popupId){
  var poppyElement = document.getElementById(popupId);

  poppyElement.className = 'hide';

}

我的问题是 - 为什么元素会闪现,并立即消失,而不是为鼠标移出事件而闲逛?

此致 阿布舍克巴克

2 个答案:

答案 0 :(得分:0)

更改JavaScript中的元素可能正在修改悬停的元素,这可能会通过更改而不是实际将鼠标移出坐标来触发鼠标输出事件。

答案 1 :(得分:0)

首先,您需要更加小心区分大小写。它应该是clientWidth(大写W)和top(小t)。其次,当您设置CSS lefttop时,您必须为该值添加+'px'后缀;一个整数本身无效。

此外,如果您想知道视口的高度,document.body是错误的查看位置。这只适用于IE Quirks模式,您通常希望避免像瘟疫一样。添加标准模式<!DOCTYPE声明,您可以跨浏览器使用document.documentElement。 (对于非IE浏览器,在window.innerHeight上分支。)

在任何情况下,除非您没有向我们展示更多CSS,否则设置lefttop样式将完全没有效果,因为.render div不是{{ 1}}。您没有显示它们是如何附加到文档的,但由于它们显然没有绝对定位,它们是文档流的一部分,并且可能导致页面在未被隐藏时移位/重排。如果这导致被移动的元素移动,它将不再位于指针下,你将立即得到一个mouseout事件。

(如果悬停物品位于弹出窗口出现的位置下方,绝对定位也会发生这种情况。)

(此外,隐藏/取消隐藏有点多余。仅保留position: absolute并将style.display设置为className'render'。)

相关问题