gpt4 book ai didi

容器 div 内的 JavaScript div 不会执行某些代码

转载 作者:行者123 更新时间:2023-11-28 04:54:49 25 4
gpt4 key购买 nike

我在容器 (div id="x1") 中有一个 div,它不会执行通过我的 doFunc() 函数分配给它的特定命令。如果我将 div 放在容器的 outside 中,代码运行得很好。我想做的是在图像的右上角制作一个“缩小图片”按钮(我使用了 CSS)。当用户单击图像时,它会变大,使用我的 large() 函数,当用户单击 X 时,图片会缩小并隐藏 X div。当 X div 位于容器 div 内时,alert("I tried!") 命令执行正常,但只有当 X div 位于其容器外部时(不在图像的右上角,我才执行调整大小命令)需要它。)任何对 HTML 和 JavaScript 有更好了解的人,你能向我解释一下我必须做什么才能让这两行代码运行而不必放弃我的“点击 X 关闭”的想法吗?

document.getElementById(containerId).style.width="300px";
document.getElementById(xId).style.display="none";

HTML-

<div class="container" id="container1" onclick="large('container1','x1')">
<img src="icecream.jpg">
<div class="x" id="x1" onclick="doFunc('container1','x1')">X</div>
</div>

JavaScript-

function large(containerId, xId){
document.getElementById(containerId).style.width="600px";
document.getElementById(xId).style.display="block";
}
function doFunc(containerId, xId){
document.getElementById(containerId).style.width="300px";
document.getElementById(xId).style.display="none";
alert("I tried!");

最佳答案

请看下面的工作代码。

The issue you had is, whenever the div x1 is clicked the event is bubbled to the parent div container1 which calls its onclick event and increases the width. Hence, when you click on x1, it calls first doFunc and reduces the width and due to event bubbling the parent got the onclick event and triggered large event which increases the width again.

因此,看起来什么都没发生。

下面已通过使用 e.stopPropagation() 停止事件冒泡来修复此问题。

function large(containerId, xId){
document.getElementById(containerId).style.width="600px";
document.getElementById(xId).style.display="inline";
}
function doFunc(e, containerId, xId){
e.stopPropagation();
e.preventDefault();
document.getElementById(containerId).style.width="300px";
document.getElementById(xId).style.display="none";
//alert("I tried!");
}
.container
{
width: 300px;
}

.x {
display: none;
cursor: pointer;
}
<div class="container" id="container1" onclick="large('container1','x1')">
<img width="100%" src="http://pisces.bbystatic.com//BestBuy_US/store/ee/2015/com/pm/nav_desktops_1115.jpg">
<div class="x" id="x1" onclick="doFunc(event, 'container1','x1')" style="float:right">X</div>
</div>

关于容器 div 内的 JavaScript div 不会执行某些代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40477154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com