HTML:
<div>点击弹出:<input id="text" /></div> <div id="showDiv" style="display:none; background-color:#666666; width: 200px; height: 100px;font-size: 14px;color:#CC0033" >DIV弹出框</div>
JS:
点击输入框,在输入框下方显示弹出框,
offset().left和offset().top获取输入框的位置,然后动态定义弹出框显示位置
$(function() { $("#text").click(function(){ var tt = $("#text"); $("#showDiv").css({position:"absolute",'z-index':80,left:tt.offset().left,top:tt.offset().top+25}); if($("#showDiv").is(':visible')){ $("#showDiv").hide(); }else{ $("#showDiv").show(); } }); });
is(':visible')和is(':hidden')都是判断对象是否可见。
is(':visible')可见的,返回true。
is(':hidden')不可见,返回true。
注:这个函数效率很低!我又在网上查了下,找到一个更好的getBoundingClientRect(),获取网页对象实际的top、bottom、left、right定位值,我们利用它计算对象的高度差,如果为0,即可认为element不可见。关键是,几乎所有浏览器都支持getBoundingClientRect。
实现 再次点击输入框,弹出框消失。