gpt4 book ai didi

jquery - 是否可以使用 .each() 数组来定位多个 div?

转载 作者:可可西里 更新时间:2023-11-01 13:14:18 24 4
gpt4 key购买 nike

只是一点免责声明:我是 jquery/javascript 编程的新手,只知道 html/css 设计的基础知识..

我一直在尝试在页面上随机放置一些 soundcloud 小部件。我似乎已经设法实现了这一点——但为此我不得不:在 css 中创建一个新的 div id,将每个小部件分配给一个单独的 div id 名称,然后编写一个函数来单独移动每个 div。我尝试使用 .each(),但从我在其他问题中收集到的信息来看,这无法通过 div 运行,只有 div.class 名称...从这里开始我对尝试 .each(); 感到非常困惑; .parent();测试中的类名等..

这是我每次都必须复制的js(只是更改'scTrack'之后的数字):

(function() {

var docHeight = $(document).height(),
docWidth = $(document).width(),
$div = $('#scTrack1'),
divWidth = $div.width(),
divHeight = $div.height(),
heightMax = docHeight - divHeight,
widthMax = docWidth - divWidth;

$div.css({
left: Math.floor(Math.random() * widthMax),
top: Math.floor(Math.random() * heightMax)
});
});

CSS:

#scTrack1 {
position:absolute;
height:70px;
width: 200px;
}

html

<div id="scTrack1">
<object height="81" width="100%"> <param name="movie" value="https://player.soundcloud.com/player.swf?url=http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F67155680&amp;show_comments=false&amp;auto_play=false&amp;color=000000"></param> <param name="allowscriptaccess" value="always"></param> <embed allowscriptaccess="always" height="81" src="https://player.soundcloud.com/player.swf?url=http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F67155680&amp;show_comments=false&amp;auto_play=false&amp;color=000000" type="application/x-shockwave-flash" width="100%"></embed> </object>
</div>

这是我在 jsfiddle 上的例子:http://jsfiddle.net/antrgor_reiz/scVRS/

我想要实现的是在 css 中定义一个 div - 用于所有不同的 soundcloud 小部件 - 以及一些 js 将循环遍历该 div 的每个实例并运行函数以重新定位 div..

这可能吗??

非常感谢!

最佳答案

您可以使用 .each() 遍历从任何选择器(有或没有类名)创建的任何 jQuery 对象。

$("div").each(function() { ... });       // loop through all divs
$("div.test").each(function() { ... } ); // loop through all divs of class "test"
$(".test").each(function() { ... }); // loop through any elements of class "test"

对于您的情况,这可以解决问题:

$(function() {    
var docHeight = $(document).height(),
docWidth = $(document).width();

// process each div that is a child of "container"
$("#container div").each(function() {

// get the current div's dimensions
var $div = $(this),
divWidth = $div.width(),
divHeight = $div.height(),
heightMax = docHeight - divHeight,
widthMax = docWidth - divWidth;

// set the current div's position
$div.css({
left: Math.floor(Math.random() * widthMax),
top: Math.floor(Math.random() * heightMax)
});
});
});

演示:http://jsfiddle.net/scVRS/62/

关于jquery - 是否可以使用 .each() 数组来定位多个 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13395676/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com