Javascript 在文本框下动态放置Div以显示选项
我有一个网页,我试图在其中放置搜索功能。在搜索框中,我放置了一个图像。当用户单击图像时,我希望显示一个包含一些内容的小div(各种过滤选项,如“搜索联系人、搜索电子邮件、搜索垃圾箱等”)。我希望将div放置在搜索框的正下方。现在我想知道我应该把这个div放在我的HTM标记中的什么地方?我想知道我怎样才能把div放在一个特定的位置上。 (像autosuggest之类的东西)。如何在javscript中处理这个问题?我的最终目标是在用户单击图像时在搜索框(文本框)下显示Div(showSearchOptions功能)Javascript 在文本框下动态放置Div以显示选项,javascript,search,positioning,Javascript,Search,Positioning,我有一个网页,我试图在其中放置搜索功能。在搜索框中,我放置了一个图像。当用户单击图像时,我希望显示一个包含一些内容的小div(各种过滤选项,如“搜索联系人、搜索电子邮件、搜索垃圾箱等”)。我希望将div放置在搜索框的正下方。现在我想知道我应该把这个div放在我的HTM标记中的什么地方?我想知道我怎样才能把div放在一个特定的位置上。 (像autosuggest之类的东西)。如何在javscript中处理这个问题?我的最终目标是在用户单击图像时在搜索框(文本框)下显示Div(showSearchO
第1项。你把新的div放在哪里并不重要,因为你会让它的位置:绝对;和显示:无;这将从文档流中删除它。然后,当它被定位和显示时,它将简单地显示在您放置它的位置。(参见答案1。)在担心javascript之前,将页面设置为所有您想要的搜索选项div,就像它是一个静态页面一样。将div设置为位置:绝对但是,代码>相对于某个容器,这样当它出现时,就不会弄乱它周围的其他元素。当绝对定位时,它在HTML代码中的位置并不重要——除了在position:relative的容器中之外代码>--因为CSS会将其定位在您想要的位置
当您对布局满意时,将该div设置为display:none然后设置javascript以在单击图像时显示它。您最好使用某种框架来帮助实现这一点。例如,在jQuery中,您可以使用如下内容:
$('img#searchImg').click(function() {
$('div#searchOptions').show();
});
不需要注册单击的
function getPosition(n,endNode){
var left = 0;
var top =0;
var node = n;
done=false;
while(!done){
if(node.offsetLeft!=null)
left += node.offsetLeft;
if(node.offsetTop!=null)
top += node.offsetTop;
if(node.offsetParent){
node = node.offsetParent;
}else{
done = true;
}
if(node == endNode)
done = true;
}
done=false;
node = n;
while(!done){
if(document.all && node.style && parseInt(node.style.borderLeftWidth)){
left += parseInt(node.style.borderLeftWidth);
}
if(document.all && node.style && parseInt(node.style.borderTopWidth)){
top += parseInt(node.style.borderTopWidth);
}
if(node.scrollLeft){
left -= node.scrollLeft;
}
if(node.scrollTop)
top -= node.scrollTop;
if(node.parentNode)
node = node.parentNode;
else
done=true;
}
return new Array(left, top);
}
function showSearchOptions(){
var tmp = document.getElementById("mysearchoptions");
var searchbox = document.getElementById("searchInputDiv"); // add that id, not just class name to html
var pos = getPosition(searchbox);
tmp.style.left = pos[0] + "px";
tmp.style.top = (pos[1] + searchbox.offsetHeight) + "px";
tmp.style.visibility = "visible";
}
$('img#searchImg').click(function() {
$('div#searchOptions').show();
});