使用鼠标悬停的图像预览JavaScript

Image preview JavaScript with mouseover

本文关键字:JavaScript 图像 鼠标 悬停      更新时间:2023-09-26

我正试图在缩略图上使用鼠标悬停事件来显示上面更大的图像。我有三个类为"preview"的图像,并且正在一个外部JS文件中编写一个函数upDate(),该函数采用参数previewPic,我想将单独div的背景图像更改为缩略图预览"x"是我想将背景图像设置为的div,"y"是我认为我出错的地方。我的代码如下:

function upDate(previewPic){
   x = document.getElementById('image');
   y = previewPic.getAttribute('src');
   x.style.backgroundImage = url('y');
}

您需要更改分配变量/string 的方式

x.style.backgroundImage = 'url(' + y + ')';

function upDate(previewPic){
  var src = previewPic.getAttribute("src");
  var alt = previewPic.getAttribute("alt");
  document.getElementById('image').style.backgroundImage = "url('" + src + "')";
  document.getElementById('image').innerHTML = alt;
}
function unDo(){
  document.getElementById('image').style.backgroundImage = "none";
  document.getElementById('image').innerHTML = "MouseOver Image to Display Here.";
}
body{
		margin: 2%;
		border: 1px solid black;
		background-color: #b3b3b3;
}
#image{
    line-height:650px;
		width: 575px;
    height: 650px;
		border:5px solid black;
		margin:0 auto;
    background-color: #8e68ff;
    background-image: url('');
    background-repeat: no-repeat;
    color:#FFFFFF;
    text-align: center;
    background-size: 100%;
    margin-bottom:25px;
    font-size: 150%;
}
.preview{
		width:10%;
		margin-left:17%;
    border: 10px solid black;
}
img{
		width:95%;
}
	<div id = "image">
		MouseOver Image to Display Here.
	</div>
	<img class = "preview"
    src = "img/image1.png"
    alt = "Image 1"
    onmouseover = "upDate(this)"
    onmouseout = "unDo()"
    >
	<img class = "preview"
    src = "img/image2.png"
    alt = "Image 2"
    onmouseover = "upDate(this)"
    onmouseout = "unDo()"
    >
	<img class = "preview"
    src = "img/image3.png"
    alt = "Image 3"
    onmouseover = "upDate(this)"
    onmouseout = "unDo()"
    >

我认为

x.style.backgroundImage = url('y');

有问题,你可以试试

x.style.backgroundImage = url(y);
x.style.backgroundImage = url('y');

在这里,您将y作为url()中的字符串传递。你需要将变量凹入,而不是字符串。

试试这个就行了

这里+符号用于连接变量。

x.style.backgroundImage = 'url(' + y + ')';

您必须在html文档中键入img标记,而不是像<img src ="yourphoto" id ="img" style ="width:100px;height:100px;"> 一样形成此文本

接下来,您应该通过javascript或Powerfull javascript库"Jquery"来触发此元素。以下是代码(请记住,您应该首先包含jquery文件)。

接下来在HTML文档或外部javascript文件中键入您的javascript,您可以选择

$(document).on('mouseover','#img',function(){
$('body').css({'background-image':'url("showimageurl")'});
return true;
});

它会正常工作。。。。。。我希望你的问题能得到解决。