新人求助: js如何自动判断gif和jpg
这是一个点击gif图片才会播放的js 演示:http://mingpin.co/gif.html代码如下:
程序代码:
var Gifffer = function() { var images, d = document, ga = 'getAttribute', sa = 'setAttribute'; images = d && d.querySelectorAll ? d.querySelectorAll('[data-gifffer]') : []; var createContainer = function(w, h, el) { var con = d.createElement('DIV'), cls = el[ga]('class'), id = el[ga]('id'); cls ? con[sa]('class', el[ga]('class')) : null; id ? con[sa]('id', el[ga]('id')) : null; con[sa]('style', 'position:relative;cursor:pointer;width:' + w + 'px;height:' + h + 'px;'); // creating play button var play = d.createElement('DIV'); play[sa]('style', 'width:60px;height:60px;border-radius:30px;background:rgba(0, 0, 0, 0.3);position:absolute;left:' + ((w/2)-30) + 'px;top:' + ((h/2)-30) + 'px;'); var trngl = d.createElement('DIV'); trngl[sa]('style', 'width:0;height: 0;border-top:14px solid transparent;border-bottom:14px solid transparent;border-left:14px solid rgba(0, 0, 0, 0.5);position:absolute;left:26px;top:16px;') play.appendChild(trngl); // dom placement con.appendChild(play); el.parentNode.replaceChild(con, el); return {c: con, p: play }; } var process = function(el) { var url, con, c, w, h, play, gif, playing = false, cc, isC; url = el[ga]('data-gifffer'); w = el[ga]('data-gifffer-width'); h = el[ga]('data-gifffer-height'); el.style.display = 'block'; c = document.createElement('canvas'); isC = !!(c.getContext && c.getContext('2d')); if(w && h && isC) cc = createContainer(w, h, el); el.onload = function() { if(isC) { w = w || el.width; h = h || el.height; // creating the container if(!cc) cc = createContainer(w, h, el); con = cc.c; play = cc.p; con.addEventListener('click', function() { if(!playing) { playing = true; gif = d.createElement('IMG'); gif[sa]('style', 'width:' + w + 'px;height:' + h + 'px;'); gif[sa]('data-uri', Math.floor(Math.random()*100000) + 1); setTimeout(function() { gif.src = url; }, 0); con.removeChild(play); con.removeChild(c); con.appendChild(gif); } else { playing = false; con.appendChild(play); con.removeChild(gif); con.appendChild(c); gif = null; } }); // canvas c.width = w; c.height = h; c.getContext('2d').drawImage(el, 0, 0, w, h); con.appendChild(c); } } el.src = url; } for(var i=0; i<images.length; i++) process(images[i]); }
这个js有个缺点,就是不管你的图片是否为gif,还是jpg,png等等格式,都会自动在图片加上一个播放的图标。求助高人是否能在此基础上加入自动判断是否为非gif格式时不在上面加播放按钮。只有当图片为gif格式时才会执行点击播放的语句。在此先谢谢了,本人是新手喜欢折腾网站,但此问题困扰很久了。