对于单个图像
您可以通过元素对象、ID 或第一src
个子字符串匹配传递图像。采用可选的目标属性,例如“_blank”。不需要 jQuery。
// By img element object
// (used by the functions below)
var addImageLink = function( elem, target ){
if( !elem || !( 'tagName' in elem ) ){ return; }
var image = elem;
var parent = image.parentElement;
var a = document.createElement( 'a' );
a.href = image.getAttribute( 'src' );
if( target ){ a.setAttribute( 'target', target ); }
a.appendChild( image );
parent.appendChild( a );
};
// By img element id
// <img src="images/gallery/1.jpg" id="image1" />
// <script> addImageLinkById( 'image1' ); </script>
var addImageLinkById = function( id, target ){
addImageLink( document.getElementById( id ), target );
};
// By img element src (first match)
// <img src="images/gallery/1.jpg"/>
// <script> addImageLinkBySrc( '/1.jpg' ); </script>
var addImageLinkBySrc = function( src, target ){
var image, images = document.getElementsByTagName( 'img' );
if( typeof src == 'undefined' ){ src = ''; }
for( var i = 0; i < images.length; i++ ){
if( images[ i ].src.indexOf( src ) < 0 ){ continue; }
addImageLink( images[ i ], target ); return;
}
};
用于遍历所有图像
此解决方案在每个图像周围放置一个链接。这是 Falko 答案的扩展版本。
- 不使用 jQuery
- 可选择通过 href 子字符串将图像列入白名单,例如“images/gallery/”
- 指定一个可选的目标属性,例如“_blank”
- 不会跳过图像的后半部分
(我在尝试他的代码时遇到了这个问题,但这可能是我做错了)
var addImageLinks = function( filter, target ){
var parent, a, image;
var images = document.getElementsByTagName( 'img' );
var hasTarget = ( typeof target != 'undefined' );
var hasFilter = ( typeof filter != 'undefined' );
for( var i = 0; i < images.length; i++ ){
image = images[ i ];
if( hasFilter && ( image.src.indexOf( filter ) < 0 ) ){ continue; }
// Skip over already-wrapped images, by adding an attribute
if( image.getAttribute( 'data-wrapped-link' ) ){ continue; }
image.setAttribute( 'data-wrapped-link', '1' );
// Add the link
parent = image.parentElement;
a = document.createElement( 'a' );
a.href = image.getAttribute( 'src' );
if( hasTarget ){ a.setAttribute( 'target', target ); }
a.appendChild( image );
parent.appendChild( a );
// We inserted a "new" image, so go back one step so we don't miss any
// (due to being inside the "i < images.length" loop)
i--;
}
};
// Then:
// <img src="images/gallery/a.jpg"/>
// <img src="images/gallery/b.jpg"/>
// <img src="images/gallery/c.jpg"/>
// <img src="images/icons/a.gif"/> <- ignored
// Near bottom of the page (or in an onLoad handler, etc):
// </script> addImageLinks( 'images/gallery/', '_blank' ); </script>