gpt4 book ai didi

javascript - onclick 函数在内联脚本中有效,但由于 window.onload = function() 而在外部 js 文件中无效。需要解决方法

转载 作者:行者123 更新时间:2023-12-03 05:24:26 25 4
gpt4 key购买 nike

由于外部js文件中的window.onload = function(){},onclick for stop不起作用。我正在尝试停止动画。在内部 js 文件中工作的代码是 var stop = setInterval(animate,60); 函数停止(){ 清除间隔(停止); }如果我在 window.onload 之外编写代码,那么它无法引用其中的 animate 函数。下面给出了 html 文件以及外部 js 文件。

<!doctype HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Cable Car</title>
<meta name="Description" content="Using Canvas">
<meta name="robots" content="noindex">
<!-- This is a HTML Comment -->
<!-- Below is the HTML Shim that uses a conditional comment -->
<!--[if lt IE 9]> <script src="dist/html5shiv.js"></script><![endif]-->
<script src="scripts/stackoverflow.js" type="text/javascript"></script>
<style>
.leftBar {
width: 15%;
height: 80%;
float: left;
}
.middleBar {
width: 60%;
height: 80%;
float: left;
margin: 20px;
}
</style>
</head>
<body>
<header role="banner">
<h1>Canvas and animation</h1>
<hr>
</header>
<aside role="complementary" class="leftBar">
<button id="stop" onclick="stop()" >Stop</button>
<p>Stop the animation</p>
</aside>
<main>
<article class="middleBar">
<canvas id="canvas" width="650" height="350"></canvas>
</article>
</main>

<footer role="contentinfo">
<hr>
<p><small>
Copyright &copy;2016. All rights reserved</small>
</p>
</footer>
</body>
</html>

下面是外部js文件

window.onload = function(){         
var cnv = document.getElementById('canvas');
var ctx = cnv.getContext('2d');

//the image object being created and loaded
var pict = new Image();
pict.src = "images/cablecar23.png";
pict.onload = function(){
ctx.drawImage(pict,0,-10,pict.width*0.25,pict.height*0.25);
}

//the moving image
x = 0;
y = -17;
/*this change variable determines how far the car moves in a redraw and direction */
change = 2;
//width and height are dimensions of the box
w = 650;
h = 100;

function animate() {
ctx.clearRect(0, 0, w, h);
ctx.drawImage(pict, x, y,pict.width*0.25, pict.height*0.25);
//checking cable car position
if(x >=630) {
//if thecar is on extreme right then it exits the screen
change = 0;
}
//update horizontal position
x = x + change;
}
//cause function to repeat with milliseconds
//calling the animate function to start the cable car
var stop = setInterval(animate,60);
//below function is not referenced
function stop(){
clearInterval(stop);
}
}

最佳答案

更改变量stop的名称,使其与函数的名称不同

onload 之外声明两者

 var intervalStop; 
function stop(){
clearInterval(intervalStop);
}

内部加载变化

 var stop = setInterval(animate,60);

 intervalStop = setInterval(animate,60);

如果您不使用内联脚本并使用unobtrusive event listeners,则不会遇到任何此问题。

关于javascript - onclick 函数在内联脚本中有效,但由于 window.onload = function() 而在外部 js 文件中无效。需要解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41213547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com