在 jQuery 中调整图像大小
我已经设置了一个小型演示,当单击图像时,它会自动调整图像大小以适合其容器 div。
它的工作原理是获取图像的大小,然后将其除以框的大小,并计算出哪个比率更高,然后根据宽度或高度相应地调整图像的大小。最好查看代码以了解其工作原理。
唯一的问题是它有点小故障。它确实有效,但不是根据图像的宽度调整大小,而是根据浏览器宽度计算图像的宽度,但仍然在调整大小时传递正确的值。
查看下面的两个链接,并尝试调整浏览器窗口的大小以查看故障。我划掉了 overflow:hidden;
属性,以便您可以看到 div 外部图像的尺寸。
看一下这里的代码: http://jsfiddle.net/sambeckhamdesign/NVAGG/11/
在此处查看全屏结果: http://jsfiddle.net/sambeckhamdesign/NVAGG/11/embedded/result/
或在此处阅读 jQuery
$('img').click(function() {
function wr(){
var imageWidth =
$(this).width()/250;
return imageWidth;
}
function hr(){
var imageHeight =
$(this).height()/200;
return imageHeight;
}
function nh(){
var newHeight =
$(this).height()/hr();
return newHeight;
}
function nw(){
var newWidth =
$(this).width()/wr();
return newWidth;
}
if (wr() > hr()){
$(this).css('width', nw() + 'px');
}else{
$(this).css('height', nh() + 'px');
}
});
I've set up a small demo that automatically resizes an image to fit inside it's container div when it is clicked.
It works by taking the size of the image then dividing that by the size of the box and working out which ratio is higher before resizing the image based on either width or height accordingly. It's probably better to look at the code to see how it works.
The only problem is that it's rather glitchy. It does work but instead of resizing based on the image's width it seems to be calculating it based on the browser width but still passing on the correct values on the resize.
Have a look at it at the two links below and have a play at resizing the browser window to see the glitch. I have crossed out the overflow:hidden;
attribute so you can see the dimensions of the image outside the div.
Take a look at the code here:
http://jsfiddle.net/sambeckhamdesign/NVAGG/11/
View the fullscreen result here:
http://jsfiddle.net/sambeckhamdesign/NVAGG/11/embedded/result/
or read the jQuery here
$('img').click(function() {
function wr(){
var imageWidth =
$(this).width()/250;
return imageWidth;
}
function hr(){
var imageHeight =
$(this).height()/200;
return imageHeight;
}
function nh(){
var newHeight =
$(this).height()/hr();
return newHeight;
}
function nw(){
var newWidth =
$(this).width()/wr();
return newWidth;
}
if (wr() > hr()){
$(this).css('width', nw() + 'px');
}else{
$(this).css('height', nh() + 'px');
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
就在我的脑海中,我敢打赌这是一个关闭问题。由于您在函数内部引用“this”,而函数也在另一个函数内部,因此“this”不会附加到图像,而是附加到窗口。您可以更新函数以传递对“this”的引用作为参数,或者设置一个作用域为引用回“this”的单击函数的变量。
Right off the top of my head, I'd bet this is a closure issue. Since you're referencing 'this' inside the functions, which are also inside of another function, 'this' isn't attached to the image but rather to the window. You could update the functions to pass a reference to 'this' as an argument, or set up a variable scoped to the click function that references back to 'this'.