我正在编写代码,这样我就可以获得随机的文章宽度。该网站已安装在WordPress上。我的php从WordPress服务器获取文章,并在页面上列出它们:
while(have_posts()) {
the_post();?>
<article id="demo" style="border:1px solid black">
<h2><?php the_title(); ?></h2>
<?php the_content(); ?>
</article>
<?php }
?>
我的ID演示文章脚本:
<script>
var x = 100/(Math.floor(Math.random() * 3)+1);
document.getElementById("demo").style.width = x + "%";
</script>
我想我需要在脚本中引入for循环,以便所有文章都能获得这种宽度变化?
使用jQuery,您可以执行以下操作(假设您已更改id="demo"
为class="demo"
)
// This fetches all elements with the class "demo" and iterates through them
$('.demo').each(function () {
// Let's generate the new width for this specific element
let newWidth = 100/(Math.floor(Math.random() * 3)+1) + '%';
// In here, "this" is the current element and we pass it into jQuery to get
// a jQuery object back just to simplify things
$(this).css({width: newWidth});
});
您可以.each()
在jQuery手册中了解更多信息
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句