我需要通过 javascript/jquery 将 width
和 height
属性添加到页面上的所有图像。这是由于我们的系统使用的工具造成的。我认为一个简单的每个循环,添加高度/宽度属性就足够了。不幸的是,这似乎不起作用
演示 https://jsfiddle.net/z86xnqd7/
$('body').find('img').each(function (index) {
var theWidth = index.width();
var theHeight = index.height();
index.attr({
"width": theWidth,
"height": theHeight
});
});
当您检查元素时,您会发现没有添加宽度/高度属性
最佳答案
jsFiddle:https://jsfiddle.net/CanvasCode/z86xnqd7/6/
您需要在加载事件中执行每个操作,您需要在检查图像的高度和宽度之前确保图像已加载。您还想使用 $(this) 而不是索引。
$(function () {
$('img').load(function () {
var theWidth = $(this).width();
var theHeight = $(this).height();
$(this).attr({
"width": theWidth,
"height": theHeight
});
});
});
关于javascript - 为所有图像添加宽度和高度属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32967527/