我试图创建一个关于排序可视化工具的反应项目, 该项目包括一个具有各种排序算法的导航栏组件和一个用于更改数组大小的滑块以及一个用于生成随机数组的生成按钮。 JSX 和 CSS 文件如下:
这是jsx页面
import React from "react";
import { useState } from "react";
import "./SortingVisualizer.css";
function SortingVisualizer() {
let [arr, setArr] = useState([]);
let [range, setRange] = useState(0);
const randomIntFromInterval = (min, max) => {
return Math.floor(Math.random() * (max - min + 1) + min);
};
const resetArray = () => {
let newArray = [];
for (let i = 0; i < range; i++) {
newArray.push(randomIntFromInterval(5, 550));
}
setArr(newArray);
};
return (
<div>
<div className="nav-bar">
<span className="range-value">{range}</span>
<input
className="range"
type="range"
name=""
value={range}
min="0"
max="150"
onChange={(event) => {
setRange(event.target.value);
}}
/>
<button onClick={resetArray}>Generate</button>
<p className='bubble-sort'>Bubble Sort</p>
<p className='selection-sort'>Selection Sort</p>
<p className='insertion-sort'>Insertion Sort</p>
<p className='quick-sort'>Quick Sort</p>
<p className='merge-sort'>Merge Sort</p>
<p className='heap-sort'>Heap Sort</p>
</div>
<div className="ice-pick">
{arr.map((num, id) => (
<div key={id} className="element" style={{ height: `${num}px` }}>
</div>
))}
</div>
</div>
);
}
export default SortingVisualizer;
这是 jsx 文件的 css 文件
.ice-pick {
text-align: center;
}
.element {
display: inline-block;
width: 5px;
margin-left: 1px;
margin-right: 1px;
background-color: rgb(77, 165, 184);
top: 40px;
}
.nav-bar {
background-color: black;
opacity: 75%;
height: 80px;
}
.range-value {
position: relative;
display: block;
margin-left: 110px;
font-size: 30px;
color: #999;
font-weight: 400;
}
.range {
width: 200px;
height: 15px;
-webkit-appearance: none;
margin-left: 20px;
background: #111;
outline: none;
border-radius: 15px;
overflow: hidden;
box-shadow: inset 0 0 5px rgba(0, 0, 0, 1);
}
.range::-webkit-slider-thumb {
-webkit-appearance: none;
width: 15px;
height: 15px;
border-radius: 50%;
background: #0dd69d;
cursor: pointer;
border: 4px solid #333;
box-shadow: -407px 0 0 400px #00e8fd;
}
button {
margin-left: 20px;
border-radius: 7px;
padding: 5px 10px;
border: none;
background-color: #00e8fd;
}
button:hover {
box-shadow: 0 0 10px 2px #00e8fd;
}
运行服务器时,导航栏的某些组件(即 div“导航栏”内的排序算法)将显示在导航栏外部。我尝试在 css 中使用各种样式,但无法解决问题。
要解决排序算法按钮显示在导航栏之外的问题,您可以尝试为导航栏使用 Flexbox 并调整按钮的样式。这是更新后的 CSS,应该将按钮保留在导航栏中:
.nav-bar {
background-color: black;
opacity: 0.75;
height: 80px;
display: flex; /* Use flexbox */
align-items: center; /* Center items vertically */
}
.nav-bar p {
margin: 0; /* Remove default margin */
padding: 0 10px; /* Add some padding for spacing */
color: white; /* Set text color to white */
}
通过这些更改,排序算法应在导航栏中水平和垂直居中,并且它们应保留在黑框内。