KP8*_*P83 7 html javascript css
我有一个两列红色/黑色网格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);
});
Run Code Online (Sandbox Code Playgroud)
.left {
left: 0;
}
.right {
right: 0;
}
.red,
.black {
width: 50%;
height: 100%;
}
.black {
position: absolute;
background-color: black;
}
.red {
position: fixed;
background-color: red;
}
Run Code Online (Sandbox Code Playgroud)
<div class="red"></div>
<div class="black"></div>
Run Code Online (Sandbox Code Playgroud)
小智 5
这是你的解决方案:
// 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);
});
Run Code Online (Sandbox Code Playgroud)
.left { left: 0;}
.right { right: 0;}
.red,
.black {
width: 50%;
height: 100%;
}
.black {
position: absolute;
background-color: black;
}
.red {
position: fixed;
background-color: red;
}
Run Code Online (Sandbox Code Playgroud)
<div class="red"></div>
<div class="black"></div>
Run Code Online (Sandbox Code Playgroud)