所以,基本上,我需要做的是从我当前所在的页面获取每个图像(在本例中我有 2 个),并且我需要向其插入一个按钮。 我尝试的方法是针对所有图像,并在其父 div 中放置一个按钮。 我尝试使用以下代码来实现此目的:
<!DOCTYPE html>
<html>
<head>
<style>
.container {
position: relative;
width: 100%;
max-width: 400px;
}
.container img {
width: 100%;
height: auto;
}
.container .btn {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
background-color: #555;
color: white;
font-size: 16px;
padding: 12px 24px;
border: none;
cursor: pointer;
border-radius: 5px;
text-align: center;
}
.container .btn:hover {
background-color: black;
}
</style>
</head>
<body>
<div class="container">
<img src="123.png">
</div>
<div class="container">
<img src="223.png">
</div>
<script type="text/javascript">
var imgscount = document.querySelectorAll("img")
var imgs_array = [...imgscount];
for(var i = 0; i< document.images.length; i++)
{
var imgs = document.querySelector("img");
for (var j = 0; j < imgs_array.length-1; j++)
{
imgs.parentElement.innerHTML = imgs.parentElement.innerHTML +'<button class="btn">Button</button>';
};
};
</script>
</body>
</html>
虽然,imgs.parentElement.innerHTML = imgs.parentElement.innerHTML +'<button class="btn">Button</button>';
在同一个 <div>
中创建两个按钮,而不是每个 <div>
1 个按钮.
这个image应该更好地解释我在这里想要实现的目标。
最佳答案
只需删除这个 for 循环
for (var j = 0; j < imgs_array.length-1; j++)
关于javascript - 在 <img> 标签的每个父 div 中插入一个按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50246102/