You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JS实现鼠标悬停文本时切换页面背景图片?

解决方法

嘿,刚学JS一周就能写出悬停切换背景的功能,已经超棒啦!关于backgroundImage的语法,你其实只差一步——需要把整个url(...)表达式用字符串包裹起来,因为JS里样式属性的值本质是字符串类型。

正确的backgroundImage语法示例

document.getElementById("bgchange").style.backgroundImage = "url('../media/battimani.jpg')";

这里要注意几个关键点:

  • 整个url(...)必须放在引号(单双均可)里
  • 图片路径里的引号要和外层引号区分开(比如外层用双引号,路径里就用单引号,反过来也可以)
  • 确保图片路径是正确的相对路径/绝对路径,否则图片会加载失败

修改后的完整代码

下面是把你的四个函数改成切换背景图片的版本,还加了一点优化让图片显示更美观:

<div class="row">
  <div class="col-xl-4 offset-xl-4 text-center">
    <p onmouseover="return bg1();"><a href="#" class="dimen">Sfondo 1</a></p>
    <p onmouseover="return bg2();"><a href="#" class="dimen">Sfondo 2</a></p>
    <p onmouseover="return bg3();"><a href="#" class="dimen">Sfondo 3</a></p>
    <p onmouseover="return bg4();"><a href="#" class="dimen">Sfondo 4</a></p>
  </div>
</div>
</body>
<script>
function bg1(){
  const bgElement = document.getElementById("bgchange");
  bgElement.style.backgroundImage = "url('../media/你的图片1.jpg')";
  // 优化图片显示,避免拉伸变形
  bgElement.style.backgroundSize = "cover";
  bgElement.style.backgroundPosition = "center";
}
function bg2(){
  const bgElement = document.getElementById("bgchange");
  bgElement.style.backgroundImage = "url('../media/你的图片2.jpg')";
  bgElement.style.backgroundSize = "cover";
  bgElement.style.backgroundPosition = "center";
}
function bg3(){
  const bgElement = document.getElementById("bgchange");
  bgElement.style.backgroundImage = "url('../media/你的图片3.jpg')";
  bgElement.style.backgroundSize = "cover";
  bgElement.style.backgroundPosition = "center";
}
function bg4(){
  const bgElement = document.getElementById("bgchange");
  bgElement.style.backgroundImage = "url('../media/你的图片4.jpg')";
  bgElement.style.backgroundSize = "cover";
  bgElement.style.backgroundPosition = "center";
}
</script>

小提示

  • 记得把代码里的你的图片1.jpg这类占位符换成你实际的图片文件名哦
  • 如果图片加载不出来,可以检查路径:比如当前HTML文件在根目录,图片在media文件夹下,就把路径改成./media/xxx.jpg(当前目录下的media文件夹)
  • 重复代码可以抽成通用函数,比如function changeBg(imagePath) { ... },然后四个悬停事件调用changeBg('对应路径'),这样代码更简洁,适合后续学习优化~

内容的提问来源于stack exchange,提问作者Thomas Passafiume

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 11:42:49