双色球
动画:
相关代码:
<div class="box"></div>
<button onclick="shuaxin()" style="margin-top: 10px">抽奖</button>
<script>
function shuaxin() {
//放红球
let arr = [];
//放全部
let res = [];
for (let i = 1; i <= 33; i++) {
arr.push(i);
}
for (let i = 0; i < 6; i++) {
let index = Math.floor(Math.random() * arr.length);
res.push(arr[index]);
arr.splice(index, 1);
}
//排序
res.sort((a, b) => a - b);
//生成蓝色球随机数
let blue = Math.floor(Math.random() * 16) + 1;
res.push(blue);
let box = document.querySelector(".box");
let box_content = box.children.length;
if (box_content !== 0) {
box.innerHTML = "";
}
res.forEach((item) => {
let ball = document.createElement("div");
ball.textContent = item;
box.append(ball);
});
}
window.onload = shuaxin;
</script>
选项卡
动画:
相关代码:
<script>
function show() {
let ul = event.currentTarget;
let li = event.target;
[...ul.children].forEach((item) => item.classList.remove("active"));
li.classList.add("active");
let content = document.querySelectorAll(".content");
content.forEach((item) => item.classList.remove("active"));
[...content]
.find((item) => item.dataset.index === li.dataset.index)
.classList.add("active");
}
</script>
购物车
动画:
相关代码:
<script>
function checkAll() {
//全选按钮状态
let status = event.target.checked;
//子商品状态
document
.querySelectorAll(".list li input[type='checkbox']")
.forEach((item) => (item.checked = status));
autoCalculate();
}
function checkItems() {
//全部商品
let items = document.querySelectorAll(
".list li input[type='checkbox']"
);
//判断状态
let status = [...items].every((item) => item.checked === true);
document.querySelector(".check-all").checked = status;
autoCalculate();
}
const nums = document.querySelectorAll(".num");
//商品是否被选中
function goodStatus(numArr) {
let items = document.querySelectorAll(
".list li input[type='checkbox']"
);
return numArr.map((num, index) => {
if (items[index].checked === false) {
return (num = 0);
} else {
return num;
}
});
}
//计算总数量
function getTotalNum(numArr) {
numArr = goodStatus(numArr);
return numArr.reduce((acc, cur) => acc + cur);
}
//计算每个商品金额
function getAmount(numArr, priceArr) {
return numArr.map((num, index) => num * priceArr[index]);
}
//总金额
function getTotalAmount(amountArr) {
amountArr = goodStatus(amountArr);
return amountArr.reduce((acc, cur) => acc + cur);
}
//自动计算
function autoCalculate() {
//数量数组
const numArr = [...nums].map((num) => parseInt(num.value));
//单价数组
const prices = document.querySelectorAll(".price");
const pricesArr = [...prices].map((price) =>
parseInt(price.textContent)
);
//金额数组
const amountArr = getAmount(numArr, pricesArr);
document.querySelector(".total-num").textContent = getTotalNum(numArr);
document.querySelector(".total-amount").textContent =
getTotalAmount(amountArr);
//为每个商品填充金额
document
.querySelectorAll(".amount")
.forEach((amount, index) => (amount.textContent = amountArr[index]));
}
//自动加载
window.onload = autoCalculate();
//数量变化自动计算
[...nums].forEach((num) => (num.onchange = autoCalculate));
</script>