使用addEventListenerJavascript选择页面上的任何图像时,如何删除div?

如何解决使用addEventListenerJavascript选择页面上的任何图像时,如何删除div?

我的作业要求我生成带有文字的图片。它还要求我在单击时将其删除。我已经有了生成图片和文字的功能,但是单击子图像时无法删除div包装器。

我知道我可以创建addEventListener来在单击div时删除div,但是我的div当前扩展到了整行。我能够将div设置为图像的大小,但是无法使模因库看起来像样。有了对CSS定位,网格,flexbox等的更好理解,我相信我可以使它工作,但是现在,我需要继续学习!为什么单击图片后我的代码不允许我删除模因?另外,如果有人知道如何正确地将“单击以删除”悬停文本居中,我将非常感谢!

const form = document.querySelector('#addmeme');
const imageUrl = document.querySelector('#imageurlinput');
const topTextInput = document.querySelector('#tptextinput');
const bottomTextInput = document.querySelector('#btmtextinput');
const submitBtn = document.querySelector('#submitbutton');
const images = document.getElementsByTagName('img');

form.addEventListener('submit',function(e) {
    // prevent website change
    e.preventDefault();
    // create new meme div and append as child to new meme library
    const newMeme = document.createElement('div');
    const memeLibrary = document.querySelector('#memeLibrary');
    newMeme.classList.add("meme");
    memeLibrary.appendChild(newMeme);
    // create img element. add class and the image's URL to the img
    const memeImage = document.createElement('img');
    memeImage.classList.add("memepic");
    memeImage.src = imageUrl.value;
    newMeme.appendChild(memeImage);
    // create div for the toptext of meme and add class and innterHTML of user's input
    const topText = document.createElement('div');
    topText.classList.add("toptext");
    topText.innerHTML = topTextInput.value;
    newMeme.appendChild(topText);
    // create div for the text when user hovers over the image
    const hoverText = document.createElement('div');
    hoverText.classList.add("hoverText");
    hoverText.innerHTML = "Click to Delete";
    newMeme.appendChild(hoverText);
    // create div for the bottom text of meme and add class and innterHTML of user's input
    const bottomText = document.createElement('div');
    bottomText.classList.add("bottomtext");
    bottomText.innerHTML = bottomTextInput.value;
    newMeme.appendChild(bottomText);
    // clear the input fields
    imageUrl.value = '';
    topTextInput.value = '';
    bottomTextInput.value = '';
})

// delete meme when clicked
images.addEventListener("click",function(e) {
    e.target.parentElement.remove();
  })
@import url('https://fonts.googleapis.com/css2?family=Poppins&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap');


body{
    background-color: #E1EFE6;
    margin: 0px;
}

#title{
    text-align: center;
    color: #000411;
    font-family: 'Poppins','Roboto';
    font-size: 3em;
    margin: 20px 0px 0px 0px;
}

#instructions{
    text-align: center;
    color: #000411;
    font-family: 'Roboto';
    font-size: 1em;

}

.userinputsection{
    margin: 20px auto;
    width: 500px;
}
.userinputsection input{
    display: inline-block;
    text-align: left;
    float: right;
    width: 360px;
}

.userinputsection label{
    display: inline-block;
    text-align: right;
    font-family: 'Roboto';
    font-size: 1em;
}

#submitbuttondiv{
    margin: 10px auto;
    display: inline-block;
}

#submitbutton{
    font-family: 'Roboto';
}

#memeLibrary{
    display: flexbox;
    padding: 5px;
    background-color: white;
    height: 100%;
    width: 100%;
}

.meme{
    position: relative;
    max-width: 400px;
    margin: 10px auto;
    

}

.memepic{
    max-width: 400px;
    border-radius: 10px;
    border-width: 1px 0px 0px 1px;
    border-color: lightgray;
    border-style: solid;
    box-shadow: 5px 5px 2px lightgrey;
    opacity: 1;

}

.memepic:hover{
    opacity: 0.5;
    transition: .5s ease;
}

.toptext{
    position: absolute;
    color: white;
    -webkit-text-stroke: 2px black;
    font-size: 2em;
    font-family: Impact;
    width: 100%;
    text-align: center;
    top: 0px;
    margin-top: 10px;
}

.memepic:hover ~ .toptext{
    -webkit-text-stroke: 2px gray;
    transition: .5s ease
}


.bottomtext{
    position: absolute;
    color: white;
    -webkit-text-stroke: 2px black;
    font-size: 2em;
    font-family: Impact;
    width: 100%;
    text-align: center;
    bottom: 0px;
    margin-bottom: 10px;
}

.memepic:hover ~ .bottomtext{
    -webkit-text-stroke: 2px gray;
    transition: .5s ease
}

.hoverText{
    visibility: hidden;
    opacity: 0;
    position: absolute;
    color: black;
    font-size: 2em;
    font-family: Poppins;
    width: 100%;
    text-align: center;
    vertical-align: middle;
    top: 50%;
    margin: 0;
    padding: 0;
}

.memepic:hover ~ .hoverText{
    visibility: visible;
    opacity: 1;
    transition: .5s ease;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <title>Meme Generator</title>
  <link rel="stylesheet" href="Meme.css">
</head>

<body>
    <h1 id="title">Meme Generator</h1>
    <h1 id="instructions">Fill out the form below to create memes!</h1>
<form action = "" id="addmeme" name="addmeme">
    <div class="userinputsection">
        <label for="imageurlinput">Image URL</label>
        <input type="text" name="imageurlinput" id="imageurlinput"></br>
    </div>
    <div class="userinputsection">
        <label for="tptextinput">Text on Top</label>
        <input type="text" name="tptextinput" id="tptextinput"></br>
    </div>
    <div class="userinputsection">
        <label for="btmtextinput">Text on Bottom</label>
        <input type="text" name="btmtextinput" id="btmtextinput"></br>
    </div>
    <div id="submitbuttondiv">
        <input type="submit" id="submitbutton" value="Create Meme!"></br>
    </div>
</form>
<div id="memeLibrary">
    <div class="meme">
        <img class="memepic" src="https://cdn.jpegmini.com/user/images/slider_puffin_before_mobile.jpg" alt="Puffin">
        <div class="toptext">THIS IS THE TOP TEXT</div>
        <div class="hoverText">Click to delete</div>
        <div class="bottomtext">THIS IS THE BOTTOM TEXT</div>
    </div>
    <div class="meme">
        <img class="memepic" src="https://dickinsoncountyconservationboard.com/wp-content/uploads/sites/2/2019/01/Common_Snapping_Turtle_36290540871-1024x767.jpg" alt="Puffin">
        <div class="toptext">THIS IS THE TOP TEXT</div>
        <div class="hoverText">Click to delete</div>
        <div class="bottomtext">THIS IS THE BOTTOM TEXT</div>
    </div>
</div>

  <script src=Meme.js></script>
</body>
</html>

解决方法

您无法将侦听器添加到NodeList

// getElementsByTagName returns a NodeList
const images = document.getElementsByTagName('img');

// blows up
images.addEventListener("click",function(e) {
  e.target.parentElement.remove();
})

但是,您可以iterate over个项目并将侦听器添加到每个条目:

const images = document.getElementsByTagName('img');

images.forEach(img => img.addEventListener("click",function(e) {
  e.target.parentElement.remove();
}))

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-