[英]Image preview JavaScript with mouseover
我正在尝试在缩略图上使用mouseover事件以在上方显示大图。 我有三个带有“ preview”类的图像,并在外部JS文件中编写了一个函数upDate(),该函数带有参数PreviewPic,我想将单独div的背景图像更改为缩略图预览。 “ x”是我要设置背景图像的div,“ y”是我认为我做错的地方。 我的代码如下:
function upDate(previewPic){
x = document.getElementById('image');
y = previewPic.getAttribute('src');
x.style.backgroundImage = url('y');
}
您需要更改分配变量/字符串的方式
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;
});
它将工作正常……希望您的问题得到解决。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.