我正在使用clip:rect将图像剪切成缩略图,并且我想将鼠标悬停在矩形上的位置随机化。我的代码:
$('.itembox').mouseover(function() {
var img = $(this).find('img');
var width = img[0].width;
var height = img[0].height;
var clipwidth = Math.floor( $(this).width() );
var clipheight = Math.floor( $(this).height() );
var widthrange = width - clipwidth;
var heightrange = height - clipheight;
var x = Math.floor(Math.random() * widthrange);
var y = Math.floor(Math.random() * heightrange);
var x2 = x + clipwidth;
var y2 = y + clipheight;
img.css('clip', 'rect('+x+'px '+x2+'px '+y+'px '+y2+'px)');
$(this).children('.itemboxbg').show();
$(this).css({'color' : 'white'});
});
可以与预设的CSS配合使用:
.itemboxbg {
border: none;
position:absolute;
width:193px;
height:273px;
z-index:0;
}
.itemboxbg img {
border: none;
position: absolute;
clip: rect(0px 193px 273px 0px);
}
但是,当触发翻转事件并更改CSS时,图像就会消失。 CSS很好,例如:
<img src="./img/exampleimage.png" style="clip: rect(304px 498px 72px 344px);">
任何帮助,将不胜感激。
最佳答案
傻了,应该是:
img.css('clip', 'rect('+y+'px '+x2+'px '+y2+'px '+x+'px)');
由于定义了clip:rect
rect(<top> <right> <bottom> <left>);
其中
<top>
和<bottom>
指定距框顶部边界的距离,而<right>
和<left>
指定距框左侧边界的距离。不过,这还不是解决方案,因为该图片未出现在框内,所以也许我应该使用背景位置
编辑:可以更改绝对的左和上位置,将图像移回到框中:
img.css('left', -x+'px');
img.css('top', -y+'px');