[英]Styling Divs with Javascript Vars
I'm doing a little experiment trying to randomly place images inside a div using a javascript loop. 我正在做一个小实验,尝试使用javascript循环将图像随机放置在div中。 I've been having some trouble with it. 我一直在遇到麻烦。
Here's what I have (simplified): 这是我(简化)的内容:
for(var i = 0; i < 10; i++)
{
var top = random(-20, 20);
var left = random(-20, 20);
document.write(
<div class="one" style="\"left:" + left + ";\"">
<img src="hein.png"/>
</div>
);
}
The goal being to generate some top and left values, and every itteration display a new image with these generated values. 目标是生成一些顶部和左侧的值,并且每个信号通知都会使用这些生成的值显示一个新图像。 I know it's a syntax error with the style="". 我知道这是style =“”的语法错误。 But nothing I've tried has worked 但是我没有尝试过
How can I get this working. 我该如何工作。
您需要将整个document.write
输出包装在引号中,如下所示:
document.write('<div class="one" style="left:"' + left + ';"><img src="hein.png"/></div>');
You should first consider using a JavaScript library like jQuery. 您首先应该考虑使用JavaScript库,例如jQuery。 This will simplify your work. 这将简化您的工作。
Let's say you have this markup 假设您有这个标记
<div id="image-container">
</div>
Include jQuery in you markup 在您的标记中包含jQuery
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>
From JavaScript you would do this, after you've included jQuery in your markup 在标记中包含jQuery之后,您可以使用JavaScript执行此操作
for(var i = 0; i < 10; i++) {
var top = random(-20, 20);
var left = random(-20, 20);
$('#image-container').append('<img src="hein.png" style="position: absolute; top: '+top+'; left : '+left +';" />');
}
You forgot the quotes in document.write
and you are escaping wrong characters inside of it 您忘记了document.write
的引号,并且在其中转义了错误的字符
document.write(
"<div class=\"one\" style=\"left:" + left + ";\">
<img src=\"hein.png\"/>
</div>"
);
You have forgotten to quote the string in the document.write
call. 您忘记了在document.write
调用中用引号引起来。 Also you forgot the unit on the measurement. 您也忘记了测量的单位。
for(var i = 0; i < 10; i++) {
var top = random(-20, 20);
var left = random(-20, 20);
document.write(
'<div class="one" style="left:' + left + 'px;top:' + top + 'px">' +
'<img src="hein.png"/>' +
'</div>'
);
}
Using PHP Instead: 改用PHP:
<?php
// Middle coords of my div
$top = 200;
$left = 350;
for($i = 0; $i < 20; $i += 1)
{
$tran = rand(-130,170);
$lran = rand(-300,270);
// Fix line breaks
$top = $top - 49;
echo '<div style="position:relative;
display: block;
height: 49px;
width:49px;
left:' . ($left + $lran) . 'px;
top:' . ($top + $tran) . 'px;
">' . '<img src="img.png"/>' . '</div>';
}
?>
Awesome! 真棒! Thanks for the help with the string syntax! 感谢您对字符串语法的帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.