如何在javascript / html中调整图像大小

时间:2015-11-26 07:30:08

标签: javascript html

<!doctype html>
<html>
<head>
<title>ParallecScrolling</title>
<style type="text/css">
*{
margin: 0px;
padding: 0px;
}
#image {
    position: relative;
    z-index: -1
}
#content {
    height: 750px;
    width: 100%;
    margin-top:-10px;
    background-color:#0d0d0d;
    position: relative;
    z-index: 1;
}
</style>


<body>
<!-- <img id="image" src="img/bg.jpg" height="710px" width="100%" /> -->
<script type="text/javascript">
    var ypos,image;
    function parallex() {
        image = document.getElementById('image');
        ypos = window.pageYOffset;
        image.style.top = ypos * .7+ 'px';
    }
    window.addEventListener('scroll', parallex),false;

</script>
</head>

<script type="text/javascript">
var imlocation = "img/";
 var currentdate = 0;
 var image_number = 0;
 function ImageArray (n) {
   this.length = n;
   for (var i =1; i <= n; i++) {
     this[i] = ' '
   }
 }
 image = new ImageArray(6)
 image[0] = 'bg.jpg'
 image[1] = 'bg2.jpg'
 image[2] = 'bg3.jpg'
 image[3] = 'bg4.jpg'
 image[4] = 'bg5.jpg'
 image[5] = 'bg6.jpg'

 var rand = 60/image.length
 function randomimage() {
 currentdate = new Date()
  image_number = currentdate.getSeconds()
  image_number = Math.floor(image_number/rand)
  return(image[image_number])
   }
      var insert = imlocation + randomimage();
   document.write("<img src='" + insert+ "'>");
</script>
<div id="content"></div>

</body>

我正在尝试将插入图像的高度设置为710px,宽度设置为100%。我做错了什么?

我已经尝试过编辑insert.height和insert.width但这似乎不起作用。

1 个答案:

答案 0 :(得分:2)

首先,您的代码运行不正常,原因如下:

image = new ImageArray(6)
image[0] = 'bg.jpg'
image[1] = 'bg2.jpg'
image[2] = 'bg3.jpg'
image[3] = 'bg4.jpg'
image[4] = 'bg5.jpg'
image[5] = 'bg6.jpg'

var rand = 60/image.length
function randomimage() {
currentdate = new Date()
image_number = currentdate.getSeconds()
image_number = Math.floor(image_number/rand)
return(image[image_number])

正如可能会注意到的,缺少分号意味着您上面的每个陈述都没有被关闭。以上应该成为:

image = new ImageArray(6);
image[0] = 'bg.jpg';
image[1] = 'bg2.jpg';
image[2] = 'bg3.jpg';
image[3] = 'bg4.jpg';
image[4] = 'bg5.jpg';
image[5] = 'bg6.jpg';

var rand = 60/image.length;
function randomimage() {
currentdate = new Date();
image_number = currentdate.getSeconds();
image_number = Math.floor(image_number/rand);
return(image[image_number]);

让我知道如果你把它排除后现在有任何错误,我会相应地改进我的答案! :)

第2部分:

而不是:

var insert = imlocation + randomimage();
insert.height = "710px";
insert.width = "100%";
document.write("<img src='" + insert+ "'/>");

让我们使用CSS,我们有两个选择:

选项1 - 使用样式属性:

var insert = imlocation + randomimage();
document.write("<img style='height:710px;width:100%' src='" + insert + "'/>");

选项2 - 使用班级

var insert = imlocation + randomimage();
document.write("<img class='ourclass' src='" + insert + "'/>");

要完成选项2,我们现在在CSS中定义“ourclass”:

.ourclass {
     height:710px;
     width:100%
}