js的dom操作之js实现图片预览功能,手机端电脑端通用
Posted 智商不够_熬夜来凑
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js的dom操作之js实现图片预览功能,手机端电脑端通用相关的知识,希望对你有一定的参考价值。
【本想做搬运工】前端用的layui,连个可连续预览图片的实现办法都没有,那么只得自己写代码了。
【思路】
电脑端效果:
手机端效果:
实现的方式就是,传入一个图片路径数组和当前预览图片的id(或索引值),再加载图片预览,并可以(移动端滑动切换)切换预览图片。类型小程序的previewImage。那么,使用纯js写代码,就要设计到一些dom的操作了。
【代码结构】
想着方便,还是像layui一样,引入css样式代码和js代码就可以随意使用的好。一个previewImg.css和一个previewImg.js就ok了。
css代码:主要是遮罩、左右箭头和loading等待框等样式。
@CHARSET "UTF-8";
.mask
left:0;
top:0;
position:fixed;
z-index:9;
width:100%;
height:100%;
text-align:center;
background:rgba(0,0,0,0.8);
.mask img
z-index:10;
position:relative;
.leftArrow
position:absolute;
left:0;
width:50px;
height:50px;
z-index:11;
cursor:pointer;
.leftArrow:hover
color:gold
.leftArrow::after
z-index: 11;
content: "";
display: block;
width: 0;
height: 0;
border-top: 20px solid transparent;
border-bottom: 20px solid transparent;
border-right: 20px solid #E9E9E9;
position: fixed;
left: 0px;
.rightArrow
z-index:11;
position:absolute;
right:0;
width:50px;
height:50px;
cursor:pointer;
.rightArrow:hover
color:gold
.rightArrow::before
z-index:11;
content: "";
display: block;
width: 0;
height: 0;
border-top: 20px solid transparent;
border-bottom: 20px solid transparent;
border-left: 20px solid #fff;
position: fixed;
right: 0px;
.toastBox
position:absolute;
top:10px;
z-index:20;
font-size:2.0em;
width:auto!important;
height:auto!important;
padding-right:15px;
line-height:60px;
border-radius:6px;
background:#FFFFFF;
opacity:0.95;
box-shadow: 0px 20px 10px rgba(0,0,0,0.6)
.toastBox::before
content:"!";
line-height:60px;
font-weight:bold;
font-size:2.0em;
color:#39F;
.loading
z-index:100;
width: 80px;
height: 40px;
margin: 0 auto;
position:relative;
.loading span
display: inline-block;
width: 8px;
margin:4px;
height: 100%;
border-radius: 4px;
background: lightgreen;
-webkit-animation: load 1.04s ease infinite;
@-webkit-keyframes load
0%,100%
height: 40px;
background: lightgreen;
50%
height: 60px;
margin-top: -20px;
background: lightblue;
.loading span:nth-child(2)
-webkit-animation-delay:0.13s;
.loading span:nth-child(3)
-webkit-animation-delay:0.26s;
.loading span:nth-child(4)
-webkit-animation-delay:0.39s;
.loading span:nth-child(5)
-webkit-animation-delay:0.52s;
js代码:类似一个操作类,使用时 new imgShow(图片路径数组,索引值)就可以了,还可以优化一下。
/**
* @author:Mr.chen
* @hint:图片预览
*/
function imgShow(srcArr,index)
//var _img=new Image();
var isPc=IsPC();
var _img=document.createElement("img");
_img.src=srcArr[index];
_img.setAttribute("id","preImg");
var _index=index;
var _winWidth=window.innerWidth;
var _winHeight=window.innerHeight;
var mask = document.createElement("div");
mask.setAttribute("class", "mask");
mask.setAttribute("id", "mask");
document.body.append(mask);
//生成Loading
var span=document.createElement("span");
var span1=document.createElement("span");
var span2=document.createElement("span");
var span3=document.createElement("span");
var span4=document.createElement("span");
var loadingBox=document.createElement("div");
loadingBox.setAttribute("class","loading");
loadingBox.setAttribute("id","loading");
loadingBox.style.display="none";
mask.append(loadingBox);
loadingBox.append(span);
loadingBox.append(span1);
loadingBox.append(span2);
loadingBox.append(span3);
loadingBox.append(span4);
//loadingBox.style.left=((_winWidth/2)-loadingBox.offsetWidth)+'px';
loadingBox.style.top=(_winHeight/2)+'px';
loadingBox.style.display="block";
//生成提示框
var toastBox=document.createElement("div");
toastBox.setAttribute("class","toastBox");
toastBox.style.display="none";
toastBox.setAttribute("id","toastBox");
toastBox.innerhtml='已经是第一张了';
if(!isPc)//手机端
toast('左右滑动切换,上滑关闭')
var interval,timeout;//动画
//添加toastBox
mask.append(toastBox);
toastBox.style.left=((_winWidth/2)-(toastBox.offsetWidth/2))+'px';
//生成左右箭头
var leftArrow=document.createElement("div");
leftArrow.setAttribute("class","leftArrow");
leftArrow.setAttribute("id","leftArrow");
leftArrow.style.top=((_winHeight/2)-10)+'px';
var rightArrow=document.createElement("div");
rightArrow.setAttribute("class","rightArrow");
rightArrow.setAttribute("id","rightArrow");
rightArrow.style.top=((_winHeight/2)-10)+'px';
//添加左右箭头
mask.append(leftArrow);
mask.append(rightArrow);
_img.onload=function()
loadingBox.style.display="none";
var imgWidth=_img.width,imgHeight=_img.height;
var ke=imgWidth/imgHeight;
var winWidth;
isPc?winWidth=window.innerWidth-50:winWidth=window.innerWidth;
var winHeight= window.innerHeight;
var trHeight=winWidth/ke;
if(trHeight>winHeight)
trHeight=winHeight-20;
winWidth=trHeight*ke;
_img.style.top=(winHeight-trHeight)/2+'px';
_img.width=winWidth;
_img.height=trHeight;
mask.append(_img)
//var img = "<img src='" + url + "' style='width:"+winWidth+"px;height:"+trHeight+"px'/>";
console.log(winWidth+','+trHeight)
_img.onClick=(function()
alert('this')
)
document.getElementById("leftArrow").addEventListener('click',function(e)
if(_index>=1)
_index--;
_img.src=srcArr[_index];
else
toast('已经是第一张了!');
event.stopPropagation();
)
document.getElementById("rightArrow").addEventListener('click',function(e)
//showAnimation();
if(_index<(srcArr.length-1))
_index++;
_img.src=srcArr[_index];
else
toast('已经最后一张了!');
event.stopPropagation();
)
/**
* 监听左右滑动
*/
var startX,startY,X,Y;
_img.addEventListener("touchstart", function(e)
e.preventDefault();
startX = e.changedTouches[0].pageX,
startY = e.changedTouches[0].pageY;
);
_img.addEventListener("touchend", function(e)
e.preventDefault();
moveEndX = e.changedTouches[0].pageX,
moveEndY = e.changedTouches[0].pageY,
X = moveEndX - startX,
Y = moveEndY - startY;
if ( Math.abs(X) > Math.abs(Y) && X > 0 )
console.log("左往右滑上一张");
if(_index>=1)
_index--;
_img.src=srcArr[_index];
else
toast('已经是第一张了!');
else if ( Math.abs(X) > Math.abs(Y) && X < 0 )
console.log("右往左滑下一张");
if(_index<(srcArr.length-1))
_index++;
_img.src=srcArr[_index];
else
toast('已经最后一张了!');
else if ( Math.abs(Y) > Math.abs(X) && Y > 0)
console.log("上往下滑..其他功能");
mask.remove();
else if ( Math.abs(Y) > Math.abs(X) && Y < 0 )
console.log("下往上滑关闭预览");
mask.remove();
else
console.log("");
return false;
);
mask.onclick=(function(param)
mask.remove();
event.stopPropagation();
);
function showAnimation()
var top=toastBox.style.top;
top=top.replace("px","");
top=top*1;
console.log(top)
if(top<=50)
console.log(top)
top+=10;
console.log(top)
toastBox.style.top=top+'px';
else
console.log('完毕')
clearInterval(interval);
if(timeout!=undefined)
clearTimeout(timeout);
timeout=setTimeout(function()
toastBox.style.top=-100+'px';
toastBox.style.display="none";
,1800)
/**
* 提示
*/
function toast(text)
if(interval!=undefined)
clearInterval(interval);
var top=toastBox.style.top;
top=top.replace("px","")*1;
if(top>=30)
toastBox.style.top=-100+'px';
console.log(toastBox.style.display)
if(toastBox.style.display=="none")
toastBox.style.display="block";
toastBox.innerHTML=text;
toastBox.style.left=((_winWidth/2)-(toastBox.offsetWidth/2))+'px';
//动画
interval=setInterval(showAnimation,30)
/**
* 检查是PC端还是手机端
*/
function IsPC()
var userAgentInfo = navigator.userAgent;
var Agents = ["android", "iPhone",
"SymbianOS", "Windows Phone",
"iPad", "iPod"];
var flag = true;
for (var v = 0; v < Agents.length; v++)
if (userAgentInfo.indexOf(Agents[v]) > 0)
flag = false;
break;
return flag;
【存在的问题】
①js在append添加元素后的点击事件的问题。在不使用jquery的情况下,我是给增加的dom添加一个id,再根据id,监听点击addEventListener事件。
②切换图片时如果大小不同,则可能产生形变,那么要重新校正才行。通过原来那个_img.onload来监听加载后再获取新切换的图大小发现值并未变化,那么再new一个image对象,再监听它的加载并获取大小再赋予给原来的_img即可。
还有可以增加的功能是,通过监听鼠标滚轮改变图片大小,这个也很方便实现了
【最终版】
js
/**
* @author:Mr.chen
* @hint:图片预览
*/
/**
* @author:Mr.chen
* @hint:图片预览
*/
function imgShow(srcArr,index)
//var _img=new Image();
var isPc=IsPC();
var _img=document.createElement("img");
if(!IsNaN(index))//传入不是数字则是url
var indexArr=findArr(srcArr,index);
index=indexArr[0];
_img.src=srcArr[index];
_img.setAttribute("id","preImg");
var _index=index;
var _winWidth=window.innerWidth;
var _winHeight=window.innerHeight;
var mask = document.createElement("div");
mask.setAttribute("class", "mask");
mask.setAttribute("id", "mask");
document.body.append(mask);
//生成Loading
var span=document.createElement("span");
var span1=document.createElement("span");
var span2=document.createElement("span");
var span3=document.createElement("span");
var span4=document.createElement("span");
var loadingBox=document.createElement("div");
loadingBox.setAttribute("class","loading");
loadingBox.setAttribute("id","loading");
loadingBox.style.display="none";
mask.append(loadingBox);
loadingBox.append(span);
loadingBox.append(span1);
loadingBox.append(span2);
loadingBox.append(span3);
loadingBox.append(span4);
//loadingBox.style.left=((_winWidth/2)-loadingBox.offsetWidth)+'px';
loadingBox.style.top=(_winHeight/2)+'px';
loadingBox.style.display="block";
//生成提示框
var toastBox=document.createElement("div");
toastBox.setAttribute("class","toastBox");
toastBox.style.display="none";
toastBox.setAttribute("id","toastBox");
toastBox.innerHTML='已经是第一张了';
if(!isPc)//手机端
toast('左右滑动切换,上滑关闭')
var interval,timeout;//动画
//添加toastBox
mask.append(toastBox);
toastBox.style.left=((_winWidth/2)-(toastBox.offsetWidth/2))+'px';
//生成左右箭头
var arrowBox=document.createElement("div");
arrowBox.style.width="100px";
arrowBox.style.margin='0 auto';
arrowBox.style.height='40px';
arrowBox.style.position='fixed';
arrowBox.style.display="inline-block";
arrowBox.style.bottom='0px';
arrowBox.style.zIndex='99999';
arrowBox.style.textAlign='center';
arrowBox.style.lineHeight='40px';
arrowBox.style.left=(_winWidth/2)-50+'px';
//生成数字索引
var numBox=document.createElement("span");
numBox.style.position='absolute';
numBox.style.left=0;
numBox.style.top=0;
numBox.style.right=0;
numBox.style.bottom=0;
numBox.innerHTML=(index+1)+'/'+srcArr.length;
numBox.style.textAlign='center';
numBox.style.color='white';
numBox.style.textShadow='1px 1px 1px #000';
//arrowBox.style.background='#DBDBDB'
mask.append(arrowBox);
arrowBox.append(numBox);
//箭头
var leftArrow=document.createElement("div");
leftArrow.setAttribute("class","leftArrow");
leftArrow.setAttribute("id","leftArrow");
var rightArrow=document.createElement("div");
rightArrow.setAttribute("class","rightArrow");
rightArrow.setAttribute("id","rightArrow");
//添加左右箭头
if(!isPc)
rightArrow.style.top=((_winHeight/2)-10)+'px';
leftArrow.style.top=((_winHeight/2)-10)+'px';
mask.append(leftArrow);
mask.append(rightArrow);
else
rightArrow.style.position='absolute';
arrowBox.append(leftArrow);
arrowBox.append(rightArrow);
//添加关闭框
var closeBox=document.createElement("div");
closeBox.style.paddingLeft="20px";
closeBox.style.paddingRight="20px";
closeBox.title='关闭预览';
closeBox.style.cursor="pointer";
closeBox.style.position="absolute";
closeBox.style.top='0px';
closeBox.style.right='0px';
closeBox.innerHTML='×';
closeBox.style.color='white';
closeBox.style.fontSize='50px';
closeBox.style.zIndex='1000';
closeBox.style.background='rgb(0,0,0,0.5)';
closeBox.onclick=function()
mask.remove()
mask.append(closeBox);
_img.onload=function()
loadingBox.style.display="none";
var imgWidth=_img.width,imgHeight=_img.height;
var ke=imgWidth/imgHeight;
var winWidth;
isPc?winWidth=window.innerWidth-50:winWidth=window.innerWidth;
var winHeight= window.innerHeight;
var trHeight=winWidth/ke;
if(trHeight>winHeight)
trHeight=winHeight-20;
winWidth=trHeight*ke;
_img.style.top=(winHeight-trHeight)/2+'px';
_img.width=winWidth;
_img.height=trHeight;
mask.append(_img)
//var img = "<img src='" + url + "' style='width:"+winWidth+"px;height:"+trHeight+"px'/>";
//event.stopPropagation();
_img.onclick=function(e)
event.stopPropagation();
return false;
//滚轮放大缩小
_img.onmouseover=function(e)
event.preventDefault();
cancelDisMouseWheel()
window.onmousewheel = function(e)
var UpDown=e.wheelDelta;
var k=_img.width/_img.height;
if(UpDown>0)
_img.width+=10;
_img.height=(_img.width)/k;
else
_img.width-=10;
_img.height=(_img.width)/k;
event.stopPropagation();
_img.onmousedown = function(ev)
event.preventDefault();
//IE直接用event或者window.event得到事件本身,而在其他浏览器函数要获取到事件本身需要从函数中传入
var oevent = ev || event;
var distanceX = oevent.clientX ;
var distanceY = oevent.clientY ;
//鼠标移动
document.onmousemove = function(ev)
var oevent = ev || event;
_img.style.left =oevent.clientX - distanceX + 'px';
_img.style.top =oevent.clientY - distanceY + 'px';
;
//鼠标放开
document.onmouseup = function()
document.onmousemove = null;
document.onmouseup = null;
;
;
document.getElementById("leftArrow").addEventListener('click',function(e)
if(_index>=1)
_index--;
_img.src=srcArr[_index];
//重新绘制大小
_img.onload=imgOnloadResize();
numBox.innerHTML=(_index+1)+'/'+srcArr.length;
else
toast('已经是第一张了!');
event.stopPropagation();
)
//判断是否是数字
function IsNaN(value)
return typeof value === 'number' && !isNaN(value);
//查找数组
function findArr(a,x)
var results=[],
len=a.length,
pos=0;
while(pos<len)
pos=a.indexOf(x,pos);
if(pos===-1)//未找到就退出循环完成搜索
break;
results.push(pos);//找到就存储索引
pos+=1;//并从下个位置开始搜索
return results;
//阻止页面滚动
//阻止浏览器事件
function disabledMouseWheel()
document.addEventListener('DOMMouseScroll', scrollFunc, false);
document.addEventListener('mousewheel',scrollFunc,false);
//取消阻止浏览器事件
function cancelDisMouseWheel()
document.removeEventListener('DOMMouseScroll',scrollFunc,false);
document.removeEventListener('mousewheel',scrollFunc,false);
function scrollFunc(evt)
evt = evt || window.event;
if(evt.preventDefault)
// Firefox
evt.preventDefault();
evt.stopPropagation();
else
// IE
evt.cancelBubble=true;
evt.returnValue = false;
return false;
function imgOnloadResize()
var imgNew=new Image();
imgNew.src=srcArr[_index];
imgNew.style.display="none";
document.body.append(imgNew);
imgNew.onload=function()
var imgWidth=imgNew.width,imgHeight=imgNew.height;
var ke=imgWidth/imgHeight;
var winWidth;
var winHeight= window.innerHeight;
isPc?winWidth=window.innerWidth-50:winWidth=window.innerWidth;
var trHeight=winWidth/ke;
if(trHeight>winHeight)//如果图片高度大于宽度
trHeight=winHeight-20;
winWidth=trHeight*ke;
_img.style.top=(winHeight-trHeight)/2+'px';
_img.width=winWidth;
_img.height=trHeight;
console.log(imgWidth+','+imgHeight)
document.getElementById("rightArrow").addEventListener('click',function(e)
//showAnimation();
if(_index<(srcArr.length-1))
_index++;
_img.src=srcArr[_index];
//重新绘制大小
_img.onload=imgOnloadResize();
numBox.innerHTML=(_index+1)+'/'+srcArr.length;
else
toast('已经最后一张了!');
event.stopPropagation();
)
/**
* 监听左右滑动
*/
var startX,startY,X,Y;
_img.addEventListener("touchstart", function(e)
e.preventDefault();
startX = e.changedTouches[0].pageX,
startY = e.changedTouches[0].pageY;
);
_img.addEventListener("touchend", function(e)
e.preventDefault();
moveEndX = e.changedTouches[0].pageX,
moveEndY = e.changedTouches[0].pageY,
X = moveEndX - startX,
Y = moveEndY - startY;
if ( Math.abs(X) > Math.abs(Y) && X > 0 )
console.log("左往右滑上一张");
if(_index>=1)
_index--;
_img.src=srcArr[_index];
_img.onload=imgOnloadResize();
numBox.innerHTML=(_index+1)+'/'+srcArr.length;
else
toast('已经是第一张了!');
else if ( Math.abs(X) > Math.abs(Y) && X < 0 )
console.log("右往左滑下一张");
if(_index<(srcArr.length-1))
_index++;
_img.src=srcArr[_index];
_img.onload=imgOnloadResize();
numBox.innerHTML=(_index+1)+'/'+srcArr.length;
else
toast('已经最后一张了!');
else if ( Math.abs(Y) > Math.abs(X) && Y > 0)
console.log("上往下滑..其他功能");
mask.remove();
else if ( Math.abs(Y) > Math.abs(X) && Y < 0 )
console.log("下往上滑关闭预览");
mask.remove();
else
console.log("");
return false;
);
mask.onclick=(function(param)
mask.remove();
);
function showAnimation()
var top=toastBox.style.top;
top=top.replace("px","");
top=top*1;
console.log(top)
if(top<=50)
console.log(top)
top+=10;
console.log(top)
toastBox.style.top=top+'px';
else
console.log('完毕')
clearInterval(interval);
if(timeout!=undefined)
clearTimeout(timeout);
timeout=setTimeout(function()
toastBox.style.top=-100+'px';
toastBox.style.display="none";
,1800)
/**
* 提示
*/
function toast(text)
if(interval!=undefined)
clearInterval(interval);
var top=toastBox.style.top;
top=top.replace("px","")*1;
if(top>=30)
toastBox.style.top=-100+'px';
//console.log(toastBox.style.display)
if(toastBox.style.display=="none")
toastBox.style.display="block";
toastBox.innerHTML=text;
toastBox.style.left=((_winWidth/2)-(toastBox.offsetWidth/2))+'px';
//动画
interval=setInterval(showAnimation,30)
/**
* 检查是PC端还是手机端
*/
function IsPC()
var userAgentInfo = navigator.userAgent;
var Agents = ["Android", "iPhone",
"SymbianOS", "Windows Phone",
"iPad", "iPod"];
var flag = true;
for (var v = 0; v < Agents.length; v++)
if (userAgentInfo.indexOf(Agents[v]) > 0)
flag = false;
break;
return flag;
return
_img
css
@CHARSET "UTF-8";
.mask
left:0;
top:0;
position:fixed;
z-index:99999;
width:100%;
height:100%;
text-align:center;
background:rgba(250,250,250,0.5);
.mask img
z-index:10;
position:relative;
.leftArrow
position:absolute;
width: 0;
height: 0;
opacity:0.8em;
left:-20px;
border-width: 20px;
border-style: solid;
filter:alpha(Opacity=80);-moz-opacity:0.5;opacity: 0.5;
border-color: transparent #000 transparent transparent;
.leftArrow:hover
color:gold
/* .leftArrow::after
z-index: 11;
content: "";
display: block;
width: 0;
height: 0;
border-top: 20px solid transparent;
border-bottom: 20px solid transparent;
border-right: 20px solid #DBDBDB;
position: absolute;
*/
.rightArrow
position:absolute;
width: 0;
height: 0;
opacity:0.8em;
right:-20px;
border-width: 20px;
border-style: solid;
filter:alpha(Opacity=80);-moz-opacity:0.5;opacity: 0.5;
border-color: transparent transparent transparent #000;
.rightArrow:hover
color:gold
/* .rightArrow::before
z-index:11;
content: "";
display: block;
width: 0;
height: 0;
border-top: 20px solid transparent;
border-bottom: 20px solid transparent;
border-left: 20px solid #DBDBDB;
position: absolute;
*/
.toastBox
position:absolute;
top:10px;
z-index:20;
font-size:2.0em;
width:auto!important;
height:auto!important;
padding-right:15px;
line-height:60px;
border-radius:6px;
background:#FFFFFF;
opacity:0.95;
box-shadow: 0px 20px 10px rgba(0,0,0,0.6)
.toastBox::before
content:"!";
line-height:60px;
font-weight:bold;
font-size:2.0em;
color:#39F;
.loading
z-index:100;
width: 80px;
height: 40px;
margin: 0 auto;
position:relative;
.loading span
display: inline-block;
width: 8px;
margin:4px;
height: 100%;
border-radius: 4px;
background: lightgreen;
-webkit-animation: load 1.04s ease infinite;
@-webkit-keyframes load
0%,100%
height: 40px;
background: lightgreen;
50%
height: 60px;
margin-top: -20px;
background: lightblue;
.loading span:nth-child(2)
-webkit-animation-delay:0.13s;
.loading span:nth-child(3)
-webkit-animation-delay:0.26s;
.loading span:nth-child(4)
-webkit-animation-delay:0.39s;
.loading span:nth-child(5)
-webkit-animation-delay:0.52s;
以上是关于js的dom操作之js实现图片预览功能,手机端电脑端通用的主要内容,如果未能解决你的问题,请参考以下文章