[英]Set div width and height using an external image?
我正在尝试获取外部图像的宽度和高度,并使用该宽度和高度在页面中设置Div的宽度和高度。
我可以轻松获得图像的宽度和高度,但是由于某些奇怪的原因,我无法为我的div使用宽度/高度!
为了更好地解释这一点,我创建了这个小提琴:
https://jsfiddle.net/qtc3q6sd/2/
这是我的整个代码:
var img = new Image();
img.onload = function() {
alert(this.width + 'x' + this.width);
$("#mydiv").css("width", $(this.width()));
$("#mydiv").css("height", $(this.height()));
}
img.src = 'https://www.google.co.uk/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';
有人可以建议这个问题吗?
提前致谢。
您以错误的方式获取宽度和高度。
var img = new Image();
img.onload = function() {
alert(this.width + 'x' + this.height);
$("#droppable").css("width", this.width);
$("#droppable").css("height", this.height);
}
img.src = 'https://www.google.co.uk/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';
参见jsfiddle 。
代码的逻辑没有错。 只是语法错误。
应该是$(this).width()而不是$(this.width())
var img = new Image();
img.onload = function() {
alert(this.width + 'x' + this.width);
$("#mydiv").css("width", $(this).width());
$("#mydiv").css("height", $(this).height());
}
img.src = 'https://www.google.co.uk/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';
语法只是一点点,
尝试这个
var img = new Image();
img.onload = function() {
alert(this.width + 'x' + this.height);
$("#mydiv").css("width", this.width);
$("#mydiv").css("height", this.height);
}
img.src = 'https://www.google.co.uk/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';
这是您的解决方案。 在您的回调函数中, this
是图像
var img = new Image();
img.onload = function() {
alert(this.width + 'x' + this.height);
$("#mydiv").css("width", this.width + 'px');
$("#mydiv").css("height", this.height + 'px');
}
img.src = 'https://www.google.co.uk/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';
您的代码有两个错误。
首先,在onload函数中,“ this”代表图像对象。 您试图调用图像的with()和height()函数,但它们不是函数,而是属性。 您必须丢失'()'。
其次,当您尝试执行$(this.width())
您$(this.width())
width值封装在jQuery对象中。 您不需要它,只需使用width属性this.width
。
下面的代码将起作用:
var img = new Image();
img.onload = function() {
alert(this.width + 'x' + this.width);
$("#mydiv").css("width", this.width);
$("#mydiv").css("height", this.height);
}
img.src = 'https://www.google.co.uk/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.