3 回答

TA貢獻1890條經驗 獲得超9個贊
發生這種情況是因為<p>您擁有的標簽沒有內容。如果您將文本添加到<p>并雙擊該文本,它將起作用。
解決方案是使用div而不是p:
function getID() {
var x = document.getElementsByClassName("blueblock")[0].id;
document.getElementById("xx").innerText = x;
}
.blueblock {
width: 30%;
height: 50vh;
float: left;
background-color: lightblue;
text-align: justify;
overflow: auto;
}
<div id="xx" ondblclick="getID()">
<div class="blueblock" id="bluebl">
<p>Just some text inside of the block.</p>
</div>
</div>

TA貢獻1824條經驗 獲得超6個贊
第一個 p 元素基本上由下一個 div 元素終止,因為 ap(等效段落)不能包含 div。因此,看不到雙擊代碼,因為實際上第一個 p 元素沒有內容。
將 p 元素替換為 div 并正確終止,意味著 div 中的任何內容都會導致看到雙擊。
但是,請注意,并非所有瀏覽器都支持 ondblclick,因此我們通過使用 Javascript 將事件偵聽器添加到元素來替換它。
這是完整的片段。請注意,當您雙擊時,innerHTML 會被替換,因此如果您再次雙擊,您將在瀏覽器控制臺中看到錯誤,因為無法找到該元素 - 它不再存在。
<!DOCTYPE html>
<html>
<head>
? <title>Test</title>
? <script>
? ? function getID() {
? ? ? var x = document.getElementsByClassName("blueblock")[0].id;
? ? ? document.getElementById("xx").innerHTML = x;
? ? ? }
? </script>
? <style>
? ?.blueblock {
? ? ? width: 30%;
? ? ? height: 50vh;
? ? ? float: left;
? ? ? background-color: lightblue;
? ? ? text-align: justify;
? ? ? overflow: auto;
? ?}
? </style>
</head>
<body>
<div id="xx">
? <div class="blueblock" id="bluebl">
? ? <p>Just some text inside of the block.</p>
? </div>
? </div>
<script>
? document.getElementById('xx').addEventListener('dblclick',getID);
</script>
</body>
</html>

TA貢獻1816條經驗 獲得超6個贊
您需要具有有效的 html 元素嵌套,并且您可能應該適應這些部分中的多個部分。這是一個例子。
function getID(el) {
var x = el.getElementsByClassName("blueblock")[0].id;
document.getElementById(el.id).innerHTML = x;
}
.blueblock {
width:30%;
height:50vh;
float:left;
background-color:lightblue;
text-align:justify;
overflow:auto;
}
<div id="xx" ondblclick="getID(this)">
<div class="blueblock" id="bluebl">
<p>Just some text inside of the block.</p>
</div>
</div>
<div id="xx2" ondblclick="getID(this)">
<div class="blueblock" id="bluebl2">
<p>Just some more text inside of the block.</p>
</div>
</div>
添加回答
舉報