昨天我在初音社(www.mikuclub.cn)看到了这个效果,有些地方的图片在鼠标经过时会放大,感觉很棒,整个网页似乎生动了不少,今天我也给自己的网站添加上了这个效果。
首先分析一下原理:在图片外层套了一个容器,这个容器和图片大小一样,设置超出隐藏。然后给图片添加上放大效果就可以了。
不过初音社应用这个效果的地方的宽高是固定的,但本站文章里的图片宽高是不一致的,所以需要用JavaScript来设定外层容器的宽高。
实现步骤如下:
首先添加css样式:
.img_scale_wrap{overflow: hidden;} /*外层元素*/
.post_t img{transition:1s;} /*设置过渡时间*/
.post_t img[data-scale]:hover{transform: scale(1.2);} /*放大效果*/
然后添加JavaScript代码:
var post_img = document.querySelectorAll(".post_t img"); // 获取所有图片
if (post_img.length > 0) {
// 给图片添加缩放控制层
function set_post_img_wrap(img) {
if (img.height>=500) { // 大于一定尺寸的才添加放大效果
img.setAttribute("data-scale", ""); // 添加放大属性
var post_img_wrap = document.createElement("div");
post_img_wrap.className = "img_scale_wrap";
img.parentNode.insertBefore(post_img_wrap, img);
post_img_wrap.appendChild(img);
post_img_wrap.style.width = img.width + "px";
post_img_wrap.style.height = img.height + "px";
}
}
// 给图片添加事件
for (var i = post_img.length - 1; i >= 0; i--) {
if (post_img[i].complete) {
set_post_img_wrap(post_img[i]);
} else {
post_img[i].onload = function() {
set_post_img_wrap(this);
}
}
}
}
本文的代码也可以用在其他类型的网站上,不只是WordPress里才能用。但是移植时要按自己情况修改css选择器和js选择器。
给WordPress文章里的图片添加放大效果