javascript - 使用 div 的高度对 div 进行冒泡排序失败
问题描述
冒泡排序功能不会根据高度对 div 进行排序。谁能弄清楚这里出了什么问题 如果一开始排序正确,请尝试多次运行代码
即使条件为假,如果冒泡排序中的语句被执行
排序功能
function resolveAfterXSeconds(x) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(x);
}, x * 1000);
});
}
function swap(el1, el2) {
const style1 = window.getComputedStyle(el1);
const style2 = window.getComputedStyle(el2);
const transform1 = style1.getPropertyValue("height");
const transform2 = style2.getPropertyValue("height");
el1.style.height = transform2;
el2.style.height = transform1;
console.log(`swapped ${transform1} ${transform2}`);
}
async function bubble_sort() {
let arr = document.querySelectorAll(".bar");
for (let i = 0; i < arr.length - 1; i++) {
// let i = 0;
for (let j = 0; j < arr.length - i - 1; j++) {
arr[j].style.background = "red";
arr[j + 1].style.background = "red";
const ht1 = arr[j].style.height;
const ht2 = arr[j + 1].style.height;
if (ht1 > ht2) swap(arr[j], arr[j + 1]);
await resolveAfterXSeconds(0.5);
arr[j].style.background = "yellow";
arr[j + 1].style.background = "yellow";
}
arr[arr.length - i - 1].style.background = "green";
}
}
解决方案
变量ht1
和ht2
将是字符串对象,其值类似于“12px”。您需要解析出字符串的数字部分,然后parseInt()
将其转换为数字。然后做你的比较。
或者,这将起作用(但不推荐),parseInt("12px")
即parseInt(ht1) > parseInt(ht2)
推荐阅读
- c++ - 如何将构建的 C++ 库安装到 /usr/include?
- git - git init 没有显示'master',如何更改 git-prompt.sh 以显示我在哪个分支?
- c# - 如何将当前用户会话信息从 Web 应用程序传递到 asp.net 核心中的业务层
- c# - 为 C# 安装 Graphhopper Directions API 客户端期间出现错误
- ruby-on-rails - Rails Query 通过直通类将子类与父类结合起来
- javascript - Angular - CSS在父/子关系中不起作用
- c++ - 如何在模板中返回正确类型的数据?
- sql-server - 将具有十进制值的 varchar 字段 (LINES) 转换为 INT 值
- java - 编写 Jira 插件:如何查找在给定日期后更改的问题?
- python - centos7上请求的Python模块错误