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

标签 javascript html css

我在容器 (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/

相关文章:

javascript - 处理事件监听器的最有效方法是什么?

javascript - 如何在 JSON 中表示删除线

javascript - 获取数据 promise angularJS

javascript - 如何查看表单源

javascript - 将 JSON 对象项添加到具有相同类的 DIV

php - 表在列中显示标题而不是行

javascript - 如何在 NodeJs 中更改 package.json 中的主文件

php - 图片大小调整php代码

html - CSS 字体 rem 技巧 : 62. 5% 或 6.25%

html - 删除每隔两行的边框底线