微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 随机将类添加到两个div

我有一个两列红色/黑色网格50/50%和高度100%,并有一个脚本,可以在加载页面随机化两者的外观,所以左或右.我将两列网格后面的代码从相对位置和右边的浮动位置改为固定的绝对位置.这必须做,因为在移动时这种滚动行为这种方式更好.

下面的代码在使用浮动时工作正常,它会向左或向右添加一个类,使红色边选择一个随机边,黑色自动跟随,因为它是相对于彼此的.使用绝对和固定位置更改,它必须向左侧或右侧添加一个类才能工作.有人知道如何添加这个,所以当剩下红色时,黑色是正确的,反之亦然.

// Random red & black //

window.addEventListener('load',function() {
  // This is a ternary operator,which is just a shorthand way to 
  // do an if/else statement. This basically says,if the random number
  // is less than .5,assign "left" to the scenario variable.
  // if it is greater (or equal to),assign "right" to the variable. 
  var scenario = Math.random() < .5 ? "left" : "right";

  document.querySelector(".red",).classList.add("" + scenario);
});
.left {
  left: 0;
}

.right {
  right: 0;
}

.red,.black {
  width: 50%;
  height: 100%;
}

.black {
  position: absolute;
  background-color: black;
}

.red {
  position: fixed;
  background-color: red;
}
<div class="red"></div>
<div class="black"></div>

解决方法

这是你的解决方案:
// Random red & black //

window.addEventListener('load',function() {
// This is a ternary operator,which is just a shorthand way to 
// do an if/else statement. This basically says,if the random number
// is less than .5,assign "left" to the scenario variable.
// if it is greater (or equal to),assign "right" to the variable.
var scenario = Math.random() < .5 ? "left" : "right";
var scenario2 = scenario == "left" ? "right" : "left";

document.querySelector(".red",).classList.add("" + scenario);
document.querySelector(".black",).classList.add("" + scenario2);

});
.left { left: 0;}
.right { right: 0;}

.red,.black {
  width: 50%;
  height: 100%;
}

.black {
  position: absolute;
  background-color: black;
}

.red {
  position: fixed;
  background-color: red;
}
<div class="red"></div>
<div class="black"></div>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


什么是深拷贝与浅拷贝?深拷贝与浅拷贝是js中处理对象或数据复制操作的两种方式。‌在聊深浅拷贝之前咱得了解一下js中的两种数据类型:
前言 今天复习了一些前端算法题,写到一两道比较有意思的题:重建二叉树、反向输出链表每个节点 题目 重建二叉树: 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列 {1,2,4,7,3,5,6,8} 和中序遍历序列 {
最近在看回JavaScript的面试题,this 指向问题是入坑前端必须了解的知识点,现在迎来了ES6+的时代,因为箭头函数的出现,所以感觉有必要对 this 问题梳理一下,所以刚好总结一下JavaScript中this指向的问题。
js如何实现弹出form提交表单?(图文+视频)
js怎么获取复选框选中的值
js如何实现倒计时跳转页面
如何用js控制图片放大缩小
JS怎么获取当前时间戳
JS如何判断对象是否为数组
JS怎么获取图片当前宽高