js自定义时间轴组件
要创建一个自定义的时间轴组件,你可以使用HTML和CSS来设计布局,然后使用JavaScript来处理交互和动态更新时间轴。以下是一个简单的时间轴组件示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Custom Timeline Component</title>
<style>
.timeline {
width: 100%;
position: relative;
}
.timeline-bar {
width: 100%;
height: 10px;
background-color: #eee;
position: relative;
}
.timeline-event {
position: absolute;
width: 10px;
height: 10px;
background-color: #333;
border-radius: 50%;
}
</style>
</head>
<body>
<div id="timeline" class="timeline">
<div class="timeline-bar">
<!-- Events will be added dynamically here -->
</div>
</div>
<script>
class Timeline {
constructor(selector) {
this.container = document.querySelector(selector);
this.bar = this.container.querySelector('.timeline-bar');
}
addEvent(date) {
const event = document.createElement('div');
event.classList.add('timeline-event');
// Calculate the position of the event based on the total width of the timeline and the passed date
const totalWidth = this.bar.offsetWidth;
const eventPosition = (totalWidth / 100) * date; // Assuming `date` is a percentage value
event.style.left = `${eventPosition}px`;
this.bar.appendChild(event);
}
}
// Usage:
const timeline = new Timeline('#timeline');
timeline.addEvent(25); // Add an event at 25% of the total width
timeline.addEvent(50); // Add an event at 50% of the total width
timeline.addEvent(75); // Add an event at 75% of the total width
</script>
</body>
</html>
这个示例中,Timeline
类接受一个CSS选择器作为参数,并在构造函数中查询相应的元素。addEvent
方法接受一个日期参数,并计算该事件在时间轴上的位置。然后,它创建一个新的div
来表示事件,并将其添加到时间轴上。
你可以根据需要调整样式和逻辑,以创建更复杂的时间轴组件。
评论已关闭