我对 Javascript 编码的熟悉程度不如对 HTML 的熟悉程度。只是想问一下,如何在此代码中调整图像大小?
<script type="text/javascript">
var image1 = new Image()
image1.src = "img/img1.jpg"
var image2 = new Image()
image2.src = "img/img2.jpg"
</script>
我已经使用这段代码在 HTML 中解决了这个问题,但我不知道如何在 Javascript 中解决这个问题:
<img src="img/www.png" alt="Logo" width="250" height="150" style="position: absolute; top: 10px; left:60px;" >
非常感谢您的回复。
麦克吉姆
*抱歉,这是完整的代码:
<?php include('variables/variables.php'); ?>
<head>
<script type="text/javascript">
var image1 = new Image()
image1.src = "img/img1.jpg"
var image2 = new Image()
image2.src = "img/img2.jpg"
</script>
</head>
<body>
<p><img src="images/pentagg.jpg" width="500" height="300" name="slide" /></p>
<script type="text/javascript">
var step=1;
function slideit()
{
document.images.slide.src = eval("image"+step+".src");
if(step<2)
step++;
else
step=1;
setTimeout("slideit()",2500);
}
slideit();
</script>
</body>
这实际上是一个php文件,是从另一个php文件调用的。
最佳答案
只需这样做:
var image1 = new Image(250, 150);
所以它是new Image(width, height)
EDIT 反射(reflect)了 OP 添加的新代码
问题是您没有将图像添加到 DOM,即网页本身。 将脚本移到正文中,就在另一个脚本的上方,并将代码更改为:
var image1 = new Image(250, 150)
image1.src = "img/img1.jpg"
var image2 = new Image(350, 200)
image2.src = "img/img2.jpg"
var body = document.querySelector('body');
body.appendChild(image1);
body.appendChild(image2);
这是一个运行中的 JSBin 示例:http://jsbin.com/AzAvunOm/1/edit?html,output
所以你的代码应该是这样的(你必须根据你的需要调整它):
<?php include('variables/variables.php'); ?>
<head>
</head>
<body>
<p><img src="images/pentagg.jpg" width="500" height="300" name="slide" /></p>
<script type="text/javascript">
var image1 = new Image(250, 150)
image1.src = "img/img1.jpg"
var image2 = new Image(350, 200)
image2.src = "img/img2.jpg"
var body = document.querySelector('body');
body.appendChild(image1);
body.appendChild(image2);
</script>
<script type="text/javascript">
var step=1;
function slideit()
{
document.images.slide.src = eval("image"+step+".src");
if(step<2)
step++;
else
step=1;
setTimeout("slideit()",2500);
}
slideit();
</script>
</body>
关于javascript - 在脚本jquery中调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21499667/