想要写一个悬浮框,当划过某个区域的时候,这个悬浮框显示,光标在哪,悬浮框就在哪。
思路是:定义一个DIV,初始化时使之display: none,在光标划过指定位置时,将此DIV设置为display: block。使用onmouseover事件和onmouseout事件。
1.定义DIV
1 <div id="operationDiv" onm ouseover="showDetail();" onm ouseout="hideDetail();"> 2 <asp:CheckBoxList ID="cblComments" runat="server" OnSelectedIndexChanged="cblComments_SelectedIndexChanged" AutoPostBack="true"> 3 <asp:ListItem Text="Agree" Value="Agree" onclick="CheckCBLSimpleSelect(this)"></asp:ListItem> 4 <asp:ListItem Text="Disagree" Value="Disagree" onclick="CheckCBLSimpleSelect(this)"></asp:ListItem> 5 </asp:CheckBoxList> 6 </div>
其中onmouseover和onmouseout是我们需要用的事件,绑定对应的js方法。
2.悬浮框的显示和隐藏 js方法
悬浮框内显示的内容我已赋在hidShowDetail内。
1 //Display checked CheckBoxList number 2 function showDetail() { 3 var displayStr = document.getElementById("hidShowDetail").value; 4 var pointPosition = getCursorPosition(window.event);//get point relative position 5 document.getElementById("TotalSelectDIV").style.display = "block"; 6 document.getElementById("TotalSelectDIV").style.left = pointPosition[0] + "px"; 7 document.getElementById("TotalSelectDIV").style.top = pointPosition[1] + "px"; 8 document.getElementById("TotalSelectNum").innerText = displayStr; 9 10 } 11 12 //Hide checked CheckBoxList number 13 function hideDetail() { 14 document.getElementById("TotalSelectNum").innerText = ""; 15 document.getElementById("TotalSelectDIV").style.display = "none"; 16 }
其中getCursorPosition方法是为了获取当前光标位置,以前是用window.event.clientX + "px"和 window.event.clientY + "px"来表示光标的坐标,但因为页面滚动,获取的位置不对。后来查到了一个,不管页面如何滚动,都可以获取到实际光标的位置getCursorPosition方法。参考:https://blog.csdn.net/liangshui999/article/details/95059015
1 function getCursorPosition(event) { 2 var position = [0, 0]; 3 var scrollingPosition = getScrollingPosition(); 4 if (typeof event == "undefined") { 5 event = window.event; 6 } 7 if (typeof event.pageX != 'undefined') { 8 position = [event.pageX, event.pageY]; 9 } else { 10 position = [event.clientX + scrollingPosition[0], event.clientY + scrollingPosition[1]]; 11 } 12 return position; 13 } 14 15 function getScrollingPosition() { 16 var position = [0, 0]; 17 if (typeof window.pageXOffset != 'undefined') { 18 position = [window.pageXOffset, window.pageYOffset]; 19 } else if (typeof document.documentElement.scrollTop != 'undefined' && 20 (document.documentElement.scrollTop > 0 || document.documentElement.scrollLeft > 0)) { 21 position = [document.documentElement.scrollLeft, document.documentElement.scrollTop]; 22 } else if (typeof document.body.scrollLeft != 'undefined') { 23 position = [document.body.scrollLeft, document.body.scrollTop]; 24 } 25 return position; 26 }
标签:位置,getElementById,js,window,position,document,event,光标 From: https://www.cnblogs.com/zhangbupangpang/p/16937665.html