js实现button
使用HTML和JavaScript创建按钮
在HTML中创建一个按钮元素,并通过JavaScript添加交互功能:
<button id="myButton">点击我</button>
document.getElementById('myButton').addEventListener('click', function() {
alert('按钮被点击了!');
});
动态创建按钮
通过JavaScript动态创建按钮并添加到DOM中:
const button = document.createElement('button');
button.textContent = '动态按钮';
button.addEventListener('click', () => {
console.log('动态按钮被点击');
});
document.body.appendChild(button);
使用CSS样式美化按钮
为按钮添加基本样式:
button {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
}
button:hover {
background-color: #45a049;
}
禁用按钮功能
通过JavaScript控制按钮的禁用状态:
const button = document.getElementById('myButton');
button.disabled = true; // 禁用按钮
// 稍后启用按钮
setTimeout(() => {
button.disabled = false;
}, 3000);
按钮点击计数器
实现一个记录点击次数的按钮:

<button id="counterButton">点击次数: 0</button>
let count = 0;
const counterButton = document.getElementById('counterButton');
counterButton.addEventListener('click', () => {
count++;
counterButton.textContent = `点击次数: ${count}`;
});






