我有一个页面,其中有很多按钮。我需要做的是在按钮附近显示一个 div。我试过这个:
<style>
#noteDiv {display:none; position: absolute; background-color: white; border: 1px solid blue;}
</style>
<script>
function showNote(e) {
var x = 0, y = 0;
if (!e) e = window.event;
if (e.pageX || e.pageY) {
x = e.pageX;
y = e.pageY;
}
else if (e.clientX || e.clientY) {
x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
document.getElementById("noteDiv").style.display = "block";
document.getElementById("noteDiv").style.left = (x)+"px";
document.getElementById("noteDiv").style.top = (y-350)+"px";
}
function hideNote() {
document.getElementById("noteDiv").style.display = "none";
}
</script>
<body>
<?php
echo "<button type ='button' id = 'noteButton'>Note</button>";
echo "<script>document.getElementById('noteButton').onclick = showNote;\n";
echo "</script>";
?>
</body>
<div id='noteDiv' >
<div ><span onclick="hideNote()">Close</span></div>
<br clear="all">
<div id='noteContent' style='max-height: 30em'></div>
</div>
它确实有效。但有时页面会在页面顶部多显示一个 div,就像一条警告消息,因此 noteDiv 的位置将远离它应附加的按钮。
我的想法是获取按钮的位置,并将按钮位置的x、y值发送到函数showNote(),从那里显示noteDiv。不知道这个想法是否合理,如何获取当前点击按钮的位置并传递给javascript?
任何建议和提示将不胜感激!
最佳答案
从一开始。 在页面顶部加载 javascript 是一个非常坏主意。我将通过大量的网络文章来向您解释原因。只说一个原因,js文件在html渲染之前就被下载了(取决于浏览器),导致页面渲染速度变慢。
关于你的方法:
三个词:关注点分离。定位dom元素不属于javascript(除了一些非常罕见的情况)。 DOM 的样式包含对象的定位,属于层叠样式表,也称为CSS。
因此,如果某些内容没有以正确的方式呈现,请不要尝试使用 JavaScript 来修复它。它只会让你非常头疼。
为了获得更好的答案,请提供可以向我们显示错误的代码。
更新
这是您可能想要实现的目标的工作示例(可能未优化)。拜托,拜托,拜托,拜托...读一本关于html,css和js的书。这是完全值得的。我没有使用 php,也不需要它。
仅供记录,我个人使用的html页面的一般结构是这样的:
html
head
title
meta
styles link
styles sections
js **LIBRARIES** which need to be loaded on **TOP**
google analytics
body
html content
js **LIBRARIES** which need to be loaded on **BOTTOM**
js scripts
为了您和帮助您的人的理智,请正确缩进(这也是对正在阅读您代码的人的尊重的标志)。
这是带有片段的代码:
function toggleNote(id) {
var noteParent = document.getElementById(id);
var note = noteParent.querySelector('.note');
var display = "none";
if (note.style.display == "none" || note.style.display == "" ) {
display = "block";
}
note.style.display = display;
}
.note {
display: none;
position: relative;
background-color: white;
border: 1px solid blue;
}
.noteContent {
max-height: 30em
}
<body>
<div class="buttonContainer" id="note0">
<button id='noteButton' onclick="toggleNote('note0')">Note</button>
<div class='note'>
<div>
<button onclick="toggleNote('note0')">Close</button>
</div>
<br clear="all">
<div class='noteContent'>It's something!</div>
</div>
</div>
</body>
关于javascript - 如何在按钮中显示div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32148969/