0

我有这个 :

<div id="randomp" style="position:absolute;top:3px;left:3px;width:165px;height:29px;background:url(/logo2.png) no-repeat;background-size: 165px;"></div>

我希望每次进入页面时属性“顶部”和“左侧”都会发生变化。我的意思是有时它出现在右上角,右下角,左上角和左下角..

这是我尝试过的: http: //redzer.com.mx/tabla.html

4

2 回答 2

0

我可能会从样式为position:fixed和的 div 开始display:none

<div id="randomp" style="display:none;position:fixed;width:165px;height:29px;background:url(/logo2.png) no-repeat;background-size: 165px;"></div>

然后使用 jQuery 确定位置 CSS 设置并开启可见性

$(document).ready(function() {
    // get jQuery object for the div
    var $randomp = $('#randomp');
    // determine whether to show top or bottom, left or right
    var top = Math.round(Math.random()); // generate 0 or 1 value
    if (top === 1) {
        $randomp.css('top', '3px');
    } else {
        $randomp.css('bottom', '3px');
    }       
    var left = Math.round(Math.random());
    if (left === 1) {
        $randomp.css('left', '3px');
    } else {
        $randomp.css('right', '3px');
    }
    // show the div
    $randomp.show();
});

当然,您也可以使用服务器端代码来执行此操作,但是由于您在标签中专门询问了 javascript/jquery,因此我建议使用此解决方案。

于 2013-08-07T00:47:00.657 回答
0

我想我得到了你所需要的。

例子

每次访问页面时,我都会使用 javascript 为图像的顶部和左侧位置生成随机数。现在我将它们设置为获得 0 到 100 之间的随机数,但您可以将其更改为任何您想要的。

var random1 = Math.ceil(Math.random() * 100);
var random2 = Math.ceil(Math.random() * 100);

$(document).ready(function () {

    $('#randomp').css('top', random1);
    $('#randomp').css('left', random2);

});
于 2013-08-07T00:54:03.217 回答