帮助创建文本的随机放置

时间:2011-01-17 09:09:13

标签: javascript

我希望文本在文本框中随机显示为左,中或右。

以下是测试页面:www.creativewritingstudio.com/Home_2.html

以下是我正在使用的脚本:

<font face="helvetica" color="1b1b1b" size="5px" repeat>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Random Text w/ jQuery</title>
<style type="text/css">
#text-box {

 padding: 4px;
 width: 602px;
}
#text-content {
 color: #1b1b1b;
 text-align : center;

}
#text-reload {

 display: block;
 margin-top: 4px;
 text-align: right;
 outline: none;
}
</style>

</head>
<body>

<div id="text-box">
 <div id="text-content"></div> <!-- random text goes in ther -->

</div>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
 $(document).ready( function() {
  var textArray = [
   'Flow',
   'Precision',
   'Voice',
   'Imagery',
   'Pace',
   'Unity',
   'Word Choice',
   'Rhythm',
   'Inspiration',
   'Balance',
   'Clarity',
   'Simplicity',
   'Revision',
   'Discipline',
   'Fundamentals',
   'Dedication',
   'Practice',
  ];
  $('#text-content').loadText( textArray, 5500 ); // ( array, interval )
 });
 // custom jquery plugin loadText()
 $.fn.loadText = function( textArray, interval ) {
  return this.each( function() {
   var obj = $(this);
   obj.fadeOut( 'slow', function() { 
    obj.empty().html( random_array( textArray ) ); 
    obj.fadeIn( 'slow' );
   });
   timeOut = setTimeout( function(){ obj.loadText( textArray, interval )}, interval );
   // reload random text (if not animated) -- entirely optional, can be removed, along     with the reload link above (<a href="javascript:;" id="text-reload"><em>randomize</em></a>)
   $("#text-reload").click( function(){ 
    if( !obj.is(':animated') ) { clearTimeout( timeOut ); obj.loadText( textArray,     interval );} // animation check prevents "too much recursion" error in jQuery 
   });
  });
 }
 //public function
 function random_array( aArray ) {
  var rand = Math.floor( Math.random() * aArray.length + aArray.length );
  var randArray = aArray[ rand - aArray.length ];
  return randArray;
 }
</script>
</html>

非常感谢!

1 个答案:

答案 0 :(得分:1)

看起来真的很复杂,代码相当多。这里有一些随机对齐元素文本的JavaScript:

<div id="myid">hello</div>
<script type="text/javascript">
window.onload=function(){
    var alignarray=['left','center','right'];
    var elem=document.getElementById('myid');
    elem.style.textAlign=alignarray[Math.round(Math.random()*2)];
}
</script>

编辑:这可能更符合您的要求:

<div id="myid">hello</div>
<script type="text/javascript">
var myarray=['hello','goodbye','gone tomorrow','I like apples'];
var elem=document.getElementById('myid');
window.setInterval(function(){
    elem.innerHTML=myarray[Math.round((myarray.length-1)*Math.random())];
},1500);
</script>

此外,请注意1500表示1秒半,您可以在myarray中添加任何HTML,而不仅仅是文字。