我正在构建我的网站的产品组合。我想展示我工作的3x3网格。我试图编写一个javascript代码,将灰色块渲染为占位符,以便方块(包括镜头)的总数始终 9。
目标:
我的代码:
function inventBlank() {
// define variables
var shot = document.getElementById('shot'),
a = document.getElementById('a'),
div = document.createElement('div');
// insertAfter function
function insertAfter(referenceNode, newNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
// if existing shots is less than 9...
if (shot < 9) {
// render gray boxes until 9
for (var i = 0; i < 10; i++) {
var div = document.createElement('div');
div.className = "shot";
div.insertAfter(a, div);
// insert new element "div" after "a"
}
}
}
inventBlank();
// call anonymous function
我尝试使用它,但控制台说这是一个匿名函数!
以下是jsFiddle
基本上,它应该在跨度之后渲染灰色块。它将通过生成一个名为div的div来实现这一目的。
我非常确定for循环无效! :(
答案 0 :(得分:1)
要做一些修复,但可以作为起点
http://jsfiddle.net/InferOn/bzVQ6/
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<style>
.wrapper {
width: 960px;
margin: 0 auto;
}
img, .shot {
width: 292px;
height: 219px;
float: left;
margin: 10px;
background: #eee;
}
.clearFix{
clear:both;
}
</style>
</head>
<body>
<div class="wrapper">
<section class="main" id="main">
</section>
</div>
<script>
var shot = function (src) {
this.src = src;
};
var shots = [];
shots.push(new shot('https://d13yacurqjgara.cloudfront.net/users/332776/screenshots/1567549/weather-dribbble.jpg'));
shots.push(new shot('https://d13yacurqjgara.cloudfront.net/users/332776/screenshots/1588565/safari-yosemite-dribbble.jpg'));
shots.push(new shot('https://d13yacurqjgara.cloudfront.net/users/332776/screenshots/1573950/browsers.jpg'));
shots.push(new shot('https://d13yacurqjgara.cloudfront.net/users/332776/screenshots/1546946/blackclock-dribbble.jpg'));
shots.push(new shot(''));
shots.push(new shot(''));
shots.push(new shot(''));
shots.push(new shot(''));
shots.push(new shot(''));
function addShot(target, source) {
var div = document.createElement('div');
div.setAttribute('class', 'shot');
var img = document.createElement('img');
img.setAttribute('src', source.src);
div.appendChild(img);
target.appendChild(div);
}
function appendClear(target) {
var div = document.createElement('div');
div.setAttribute('class', 'clearFix');
target.appendChild(div);
}
var target = document.getElementById('main');
for (var i = 0; i < shots.length ; i++) {
if(i >0 && i % 3 == 0){
appendClear(target);
}
addShot(target, shots[i]);
}
</script>
</body>
</html>