js方法在加载时调用,但窗体初次加载时,该方法却没有执行,而在页面刷新时,该方法却执行了
img 元素只有当 onload (完全加载,可以显示) 的时候你才能获得它的属性 width, height, naturalWidth, naturalHeight。(naturalWidth 和 naturalHeight 是它们真实的尺寸,但 IE 6/7/8 不支持。)
你的 if 不执行是因为当 JavaScript 运行到这一行的时候 img 还没有被加载,得不到 width 和 height 属性值,瞬间就被忽略了。所以你必须等每一个 img 加载才能设置它父层 bt 的尺寸。
窗体加载的事件是 $(window).on("load", function() {/*、、、*/});,但你的情况不需要。
function LimitImg() {
$(".mo").each(function() {
var image = new Image();
// 图像加载完毕
image.onload = function() {
if (this.height 700 this.width = 454) {
$(bt).css("height", "700");
}
else if (this.width 454 this.height = 700) {
$(this).css("width", "454");
}
else if (this.width 454 this.height 700) {
$(this).css("width", "454");
var iH = 454 * (this.height) / this.width;
if (iH 700) {
$(bt).css("height", "700");
}
}
// 销毁 image 以防内存溢出
image = null;
}
// 注意 image.src 必须写在 image.onload 之后
image.src = $(this).attr("src");
});
}
使用 jQuery 的 load 也可以得到 image 的尺寸,但如果有 CSS 或父层限制,得到的 width 和 height 是不准确的。所以必须使用 new Image()。
$(".mo").each(function() {
$(this).on("load", function() {
alert($(this).width() + " " + $(this).height());
});
});
Asp.net 页面刷新,为什么会自动执行上次运行过的事件,有什么办法可以解决自动运行事件的问题?
没有弄明白你的意思?大概猜想你是在Page_Load中放了一段代码,只想执行一次,对不?请使用Session来标识某个代码是否被执行了:
Page_Load(....){ if(Session["flag"]!=null) { //表示已经执行了代码,这里不能执行了。 }}
在某个只能一次性运行的代码:Session["flag"]=true
jquery如何让页面刷新的时候默认执行一次点击事件?
如果需要在页面刷新的时候默认执行一次点击事件,可以参考下面的方法实现:
1、使用原生js实现
使用原生js主要用到了window.onload方法:
onload 事件会在页面或图像加载完成后立即发生。
语法:onload="SomeJavaScriptCode"
参数SomeJavaScriptCode是必须的规定该事件发生时执行的 JavaScript。
实现代码:
script
window.onload = function() {
requestFullScreen();//直接执行onclick中的函数就行
}
/script
将代码放到body标签最下面即可。
2、使用Jquery实现
使用jquery实现该效果主要用到了jquery.ready(fn)和jquery.trigger()方法:
jquery.ready(fn):当DOM载入就绪可以查询及操纵时绑定一个要执行的函数。
jquery.trigger(type,[data]):在每一个匹配的元素上触发某类事件。
实现代码:
$(function() {
$("#sdsd").trigger("click");//触发button的click事件
});