Javascript函数在某一行之后停止

Javascript function is stopping after a certain line

本文关键字:一行 之后 函数 Javascript      更新时间:2023-09-26

我正在尝试创建一个javascript函数,将图像裁剪并居中到1000px。要做到这一点,我取宽度,减去1000,除以2,再乘以-1。然后我取这个值并将其分配给左边距和右边距。我已将其设置为在页面加载时运行。出于某种原因,它没有执行我的第一行代码。看看下面。(调试警报用于调试目的)

Javascript

function crop()
{
alert("debug")
width = document.getElementById(slide).width
alert("debug")
width = -1((width - 1000)/2)
alert("debug")
document.getElementById(slide).setAttribute("style","margin-left" + width + "px")
alert("debug")
document.getElementById(slide).setAttribute("style","margin-right" + width + "px")
alert("debug")
}

这就是我试图让它应用所有这些的元素。

元素

<div id="mySlides" style="width:1000px; overflow:hidden;">
<img src="img/1.jpg" onclick="slideshow()" id="slide" />
</div>

正如您所看到的,它只显示第一个调试警报,之后不显示任何其他警报。有人能解释一下为什么它忽略了代码的其余部分吗?

slide是对名为slide的变量的引用。您可能想要"slide"(字符串),因为您的img元素具有id="slide"

您应该花一些时间熟悉浏览器的调试工具(alert()是一种糟糕的调试方式)。它会指出。。。

ReferenceError:幻灯片未定义

此处字符串周围缺少分隔符:

width = document.getElementById("slide").width;

这里缺少乘法运算符:

width = -1 * ((width - 1000)/2);

样式声明中缺少字符串分隔符和冒号,还必须将样式放在一起,否则第二个样式将覆盖第一个:

document.getElementById("slide").setAttribute("style","margin-left:" + width + "px;margin-right:" + width + "px");