最近和WP里面各种LightBox插件较劲,发现这些插件都需要<img>Tag之外要<a 媒体文件>来包围,不然没有Light-Box效果。少量的话可以手动修改,但如果几百个文章,图片再多一些就是灾难。只能考虑自动方法了。
自己尝试写了一些基础的JS代码,为WordPress中<img>添加<a>,大概效果为:
before:<img ...>
==>
after:<a href='img.src'><img ...></a>
下面为JS代码wrapTagImgWithA函数,当<img>中有data-LightBoxExclude属性,则该<img>跳过不追加<a>,利用HTML加载完毕时(DOMContentLoaded)加载这个函数。
/**
* wrap Tag<Img> with Tag<a href=img.src> for LightBox
* but exclude like <img data-LightBoxExclude=''> mark by
* custom attribute data-LightBoxExclude
* ------------------------------------------------------------------
* @param {string} galleryAreaID gallery-area's ID
* @return void
* @author mkland.net
*/
function wrapTagImgWithA(galleryAreaID)
{
// get gallery area object, in wordpress is (id='content') area
var oGalleryArea = document.getElementById(galleryAreaID);
// get array include <img>(without parentNode<a>)
var oImgAry = [];
if (oGalleryArea){
var imgs = oGalleryArea.getElementsByTagName('img');
for(var i=0; i < imgs.length; i++){
// exclude <img data-LightBoxExclude=''>
if (imgs[i].dataset.lightboxexclude !== undefined) continue;
if (!imgs[i].parentNode.href) oImgAry.push(imgs[i]);
}
}
// wrap <a> to <img>'s parentNode, set a.href=img.src
oImgAry.forEach(function(oImg){
var oImgWithA = document.createElement('a');
oImgWithA.href = oImg.src;
oImg.parentNode.replaceChild(oImgWithA, oImg);
oImgWithA.appendChild(oImg);
});
}
window.addEventListener("DOMContentLoaded", wrapTagImgWithA('content'));
同时,为了视觉上的效果,为<img>图片加了mouseover时style为zoom-in(IE以外都支持)。
before:<img ...>
==>
after:<img ... style="cursor:zoom-in">
以下为JS代码chgTagImgCursorToZoomIn函数,一样在HTML加载完毕时(DOMContentLoaded)加载这个函数 。<img>中有data-LightBoxExclude属性,则该<img>跳过不追加光标样式。
/**
* change cursor style to zoom-in in galleryArea's <img>
* but exclude like <img data-LightBoxExclude=''> mark by
* custom attribute data-LightBoxExclude
* ------------------------------------------------------------------
* @param {string} galleryAreaID gallery-area's ID
* @return void
* @author mkland.net
*/
function chgTagImgCursorToZoomIn(galleryAreaID)
{
// get gallery area object, in wordpress is (id='content') area
var oGalleryArea = document.getElementById(galleryAreaID);
// change cursor style to zoom-in
var imgs = oGalleryArea.getElementsByTagName('img');
for(var i=0; i < imgs.length; i++){
// exclude <img data-LightBoxExclude=''>
if (imgs[i].dataset.lightboxexclude !== undefined) continue;
imgs[i].style.cursor = 'zoom-in';
}
}
window.addEventListener("DOMContentLoaded", chgTagImgCursorToZoomIn('content'));
有想使用的朋友尽管拿去用:)一般以上函数可以直接添加到你引用的Light-Box插件的js代码头部。另外本站使用“SimpLy Gallery Block & Lightbox”这个插件,效果很棒。
–mkland.net原创