在鼠标悬停时更改img

如何解决在鼠标悬停时更改img

使用CSS可以通过:hover更改背景。 您可以使用JavaScript进行同样的操作吗?

假设您在JavaScript中附加了img,并且希望每次用户将鼠标悬停在该图像上时都可以使用CSS来更改该图像吗?我已经尝试过两种方法(使用JS和CSS进行onmouseover:悬停),但是每次“新图像”都卡在使用JavaScript创建的img后面。

是否有办法在旧版本的顶部替换“新版本的img”?

这是代码

//get api
fetch(api)
  .then(function (res) {
    return res.json();
  })
  .then(function (json) {
    dataFunction(json); 
  });

dataFunction(data){
poster.innerHTML = data.poster
}

每当我将鼠标悬停在图像上时,我想使用CSS更改背景,新的背景都会设置在API海报的背面

解决方法

您可以拥有两个图像标签onhover,可以更改图像的可见性。

.container:hover .second-img {
  visibility: visible;  /*showing second image on hover */
  opacity: 1;
}

* {
  margin: 0;
  padding: 0;
  border: 0;
}

.container {
  position: relative;
  height: 300px;
  width: 257px;
}

.second-img {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(29,106,154,0.72);
  color: #fff;
  visibility: hidden;
  opacity: 0;
  transition: opacity .3s,visibility .3s;
}

.container:hover .second-img {
  visibility: visible;
  opacity: 1;
}
<div class="container">
  <img class="first-img" src="https://dummyimage.com/300x300/000/fff&text=hover+me" />
  <img class="second-img" src="https://dummyimage.com/300x300/000/fff&text=hello" />
</div>

,

例如,如果它是背景图像,则可以使用css进行更改,例如

.myImageClass:hover {
   background-image: new_image.jpg;
}

或者您可以添加一个伪元素,例如:

.myClass::after {
   background-image: old_image.jpg;
}
.myClass:hover::after {
   background-image: new_image.jpg;
}

这取决于您的结构,我无法准确告知。

至于Javascript,我无法理解您的代码...您将JSON对象作为服务器响应,因此data.poster值可能不是正确的html代码。或者,对我来说,最好是获取带有图像源地址的平面文字,然后将其插入到img.src属性中:

poster.src = data.imageSrc;

还要验证和/或更改您的z-index,这可能是在前一张图像的背面显示新图像的原因。

,

至少有两种方法可以解决此问题。第一个纯css和第二个纯javascript。 让我们看一下第一个,您已经从data.poster获取了api,然后将其作为您命名为海报的对象的innerHtml属性插入。我不知道您的api是什么,但是可以直接将图像插入html,而可以在style标签中插入图像。让我解释一下!我认为您的data.poster可能像

data.poster = '<img src="image_url"/>'

如果您创建该api,则可以通过以下方式进行更改:

data.poster = '<div class="image_on_hover">...</div><style> .image_on_hover{background-image: url("first_url");} .image_on_hover:hover{background-image: url("second_url");} </style>'

然后将其插入,如上面的代码所示。注意,我只是使用css属性来更改背景,只需要在您的api中进行一些更改即可。这种方式不是很好,因为 您可以让您的代码插入可能有害的某个标签(也许有人在恶意script中更改您的标签)。 如果您从api获取的图像在每次加载页面时都没有改变,则可以像以前示例中一样,在style中进行硬编码,而不是使用api进行硬编码在style.css文件中。 第二种方法,您可以使用javascript做到这一点。 对于这种方法,最好将您的api仅发送这些图像的网址。

data.poster = {image1: url_of_image_one,image2: url_of_image_two}

然后您的代码必须是这样

//get api
fetch(api)
  .then(function (res) {
    return res.json();
  })
  .then(function (json) {
    dataFunction(json); 
  });

dataFunction(data){
poster.classNames.add('image_on_hover')
poster.innerHTML += 'data.poster = '<div class="image_on_hover">...</div><style> .image_on_hover{background-image: url("first_url");} .image_on_hover:hover{background-image: url("second_url");} </style>'
}

还有许多其他方法可以解决此问题,但是通常的想法是使用相同的属性来更改图像,例如,如果您已经使用了某种js框架,例如Vue,则可以在src标签的<img>中进行更改,

new Vue({
  el: '#vue-app',data:{
    image_url: '',first_url: '',second_url: '',},methods:{
    hoverOut(){
      if (this.first_url!=='')
        this.image_url = this.first_url;
    },hoverIn(){
      if (this.second_url!=='')
        this.image_url = this.second_url;
    },fetchData(){
      let that = this;
      fetch(api).then(res=>{
        that.first_url = res.poster.image1;
        that.second_url = res.poster.image2;
      })
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="vue-app">
<img :src="image_url" @mouseHover="hoverIn" @mouseout="hoverOut"/>
</div>

您还可以在here上看到此event解决方案

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 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-