如何让js在页面加载后只执行一次,也就是再次刷新当前页,不再执行js

JavaScript08

如何让js在页面加载后只执行一次,也就是再次刷新当前页,不再执行js,第1张

你的意思是刷新页面也不再执行的意思吧。

如果是这个意思,给你个思路:你需要利用cookie在客户端写一个数据,然后页面执行js之前,检查cookie中的数据是否存在,如果存在就不执行,如果没有cookie中的数据,就执行该操作。

js是每次页面加载都会被加载的。因为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())

})

})

第一次加载执行js

刷新,实现是可以实现的,但是我不知道你要达到什么样的效果。如果说只写个普通的刷新页面的js话每次加载的时候都会触发这个刷新页面。就会死循环。我没碰到过这种情况,你可以将服务器短设置个变量放入session的作用域中判断如果这个变量为1就让js刷新,否则不刷新。不知道能不能提供一些帮助。。