如何在页面加载时编辑我的代码而不是警报?
http://jsfiddle.net/SN2t6/135/
这是我的检查图像维度的代码,当加载页面时它会提醒宽度和高度。但我想编辑代码,因为页面加载时没有警报宽度和高度,警报警报宽度和点击元素的高度。
我该怎么办?
<input id="banner_img_ads" value="http://pbs.twimg.com/profile_images/1562471633/IMG_8733quadrat900px.jpg">
<br>
<br>
<div onclick="getMeta(url, callback)">
click to check
</div>
<script>
function getMeta(url, callback) {
var img = new Image();
img.src = url;
img.onload = function() { callback(this.width, this.height); }
}
var banner_img_ads_input_val = document.getElementById("banner_img_ads").value;
getMeta(
banner_img_ads_input_val,
function(width, height)
{
alert(width);
alert(height);
}
);
</script>
答案 0 :(得分:0)
使用点击事件监听器
function getMeta(url, callback) {
var img = new Image();
img.src = url;
img.onload = function() {
callback(this.width, this.height);
}
}
var trigger = document.querySelector('.trigger');
trigger.addEventListener('click', function() {
getMeta (
document.getElementById("banner_img_ads").value,
function(width, height) {
alert(width);
alert(height);
}
);
})
&#13;
<input id="banner_img_ads" value="http://pbs.twimg.com/profile_images/1562471633/IMG_8733quadrat900px.jpg">
<br>
<br>
<div class="trigger">click to check</div>
&#13;
答案 1 :(得分:0)
您可以在隐藏元素中设置宽度和高度,然后在下面添加jquery代码。
<input type="hidden" id="widthValue">
<input type="hidden" id="heightValue">
<input id="banner_img_ads" value="http://pbs.twimg.com/profile_images/1562471633/IMG_8733quadrat900px.jpg">
<br>
<br>
<div onclick="getMeta(url, callback)">
click to check
</div>
<script>
function getMeta(url, callback) {
var img = new Image();
img.src = url;
img.onload = function() { callback(this.width, this.height); }
}
var banner_img_ads_input_val = document.getElementById("banner_img_ads").value;
getMeta(
banner_img_ads_input_val,
function(width, height)
{
$("#widthValue").val(width);
$("#heightValue").val(height);
}
);
</script>
$(document).ready(function(){
$("#YOURELEMENTID").click(function(){
alert($("#widthValue").val());
alert($("#heightValue").val());
});
});
答案 2 :(得分:0)
<input id="banner_img_ads" value="http://pbs.twimg.com/profile_images/1562471633/IMG_8733quadrat900px.jpg">
<br>
<br>
<div class="show-alert">click to check</div>
<script>
$('.show-alert').on('click', function(){
var url = $('banner_img_ads').attr('value');
var img = new Image();
img.src = url;
alert(img.width);
alert(img.height);
});
</script>
答案 3 :(得分:0)
主要原因是您需要为警报设置setTimeout,以便图像完成加载然后弹出警告框。你给这个问题一个jQuery标签,但你的代码中没有任何jQuery。确保你有良好的缩进,这有助于我们轻松阅读代码。如果你想看看你的代码是如何在jQuery中完成的
https://jsfiddle.net/trungkim2201/sug7hLdn/
setTimeout(function() {
alert("Height: " + $image.height() + ", Width: " + $image.width());
}, 100)
// give it sometime to wait for the image to load
快乐编码