在jquery中创建一个随机边界



我创建了一个随机数,在每次页面加载时,我的div的边界半径都在变化:

<script>
$(".card-body").each(function(){
var rand = Math.floor(Math.random() * 100) + 1;
$(this).css( {  borderRadius:  rand } );
});
</script>

如何像在这个css中那样设置边界半径?

border-radius: 255px 15px 225px 15px/15px 225px 15px 255px;}

使用以下代码:

循环8次,在rand上加上(+=(每次随机的第4个数字后加上/

$(".card-body").each(function(){
var rand="";
for(var i=0;i<8;i++)
{
rand += Math.floor(Math.random() * 255) + 1 + "px";
if(i!=3)
rand +=" ";
else
rand +="/ ";
}
$(this).css( {  borderRadius:  rand } );
});
.card-body-static{
border:1px solid black;
border-radius: 255px 15px 225px 15px/15px 225px 15px 255px;
margin-bottom:15px;
}
.card-body{
border:1px solid black;
margin-bottom:15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card-body-static">static</div>
<div class="card-body">random</div>
<div class="card-body">random 2</div>

以下是解决此问题的方法,它包括构造一个border-radius值的数组,然后将它们连接起来组成字符串CSS规则。

  1. 创建一个返回1到100之间的随机数的函数:

    function randomPercentage(){
    return Math.floor(Math.random() * 100);
    }
    
  2. 对于每张卡,获取其宽度

    $(".card-body").each(function(){
    const width = $(this).width();
    // ...
    });
    
  3. 然后创建一个包含两个数字的新数组([ 0, 0 ](:

    $(".card-body").each(function(){
    const width = $(this).width();
    const borderRadiusStyle = [0,0];
    // ...
    });
    
  4. 我们需要多次映射此数组才能获得数组border-radius值。首先为每个元素分配一个随机百分比(使用randomPercentage函数(。然后将每个百分比乘以对象的宽度,将其分配给一个值(这是我们的border-radius的一个很好的参考值(。另一个映射将该值与'px'字符串连接起来。最后,我们将把这两个元素连接在一起,并在两者之间留出一个空间。

    $(".card-body").each(function(){
    const width = $(this).width();
    const borderRadiusStyle = [0,0];
    .map(value => randomPercentage())
    .map(percentage => width*percentage)
    .map(pixels => pixels + 'px')
    .join(' ');
    // ...
    });
    
  5. 然后,您可以将属性分配给对象:

    $(".card-body").each(function(){
    const width = $(this).width();
    const borderRadiusStyle = [0,0];
    .map(value => randomPercentage())
    .map(percentage => width*percentage)
    .map(pixels => pixels + 'px')
    .join(' ');
    $(this).css( {  borderRadius:  borderRadiusStyle });
    });
    

以下是完整的代码片段:

function randomPercentage(){
	return Math.floor(Math.random() * 100);
}
$(".card-body").each(function(){
	
const width = $(this).width();
	const borderRadiusStyle = [0,0]
.map(value => randomPercentage())
.map(percentage => width*percentage)
		.map(pixels => pixels + 'px')
.join(' ');

	$(this).css( {  borderRadius:  borderRadiusStyle });

});
.card-body {
width: 200px;
height: 100px;
background-color: purple;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card-body"></div>
<div class="card-body"></div>

最新更新