第二周:事件监听 + 用户交互
事件监听是JavaScript响应用户操作的核心机制。当用户与网页交互时(如点击、输入、按键等),浏览器会生成事件,我们可以通过监听这些事件来执行相应的代码。
element.addEventListener(eventType, callback, options);
eventType: 要监听的事件类型(如'click', 'keydown')callback: 事件触发时执行的函数options: 可选参数对象
javascript
复制
下载
element.removeEventListener(eventType, callback);
用于移除之前添加的事件监听器
常用事件类型
click: 鼠标点击
input: 输入框内容变化
change: 表单元素值改变
keydown: 键盘按键按下
load: 资源加载完成
mouseover/mouseout: 鼠标移入/移出
mousedown/mouseup: 鼠标按下/释放
contextmenu: 右键菜单
点击事件
// ==UserScript==
// @name 点击事件示例
// @namespace http://tampermonkey.net/
// @version 1.0
// @description 学习click事件监听
// @match *://*/*
// @grant none
// ==/UserScript==(function() {
'use strict';
// 创建测试按钮
const btn = document.createElement('button');
btn.textContent = '点击我测试';
btn.style.cssText = `
position: fixed;
top: 10px;
left: 10px;
z-index: 10000;
padding: 10px;
background: #007cba;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
`;
document.body.appendChild(btn);
// 添加click事件监听
btn.addEventListener('click', function(event) {
console.log('按钮被点击了!');
alert('你点击了按钮!');
// event对象包含事件信息
console.log('事件类型:', event.type);
console.log('点击位置:', event.clientX, event.clientY);
});
// 移除事件监听的例子(不执行,只是展示)
// btn.removeEventListener('click', clickHandler);
})();
// ==UserScript==
// @name 键盘事件示例
// @namespace http://tampermonkey.net/
// @version 1.0
// @description 学习键盘事件监听
// @match *://*/*
// @grant none
// ==/UserScript==(function() {
'use strict';
let keyInfo = document.createElement('div');
keyInfo.style.cssText = `
position: fixed;
top: 10px;
right: 10px;
background: #333;
color: white;
padding: 10px;
border-radius: 5px;
z-index: 10000;
font-family: monospace;
`;
document.body.appendChild(keyInfo);
// keydown - 按键按下时触发
document.addEventListener('keydown', function(e) {
console.log('按键按下:', e.key, 'KeyCode:', e.keyCode);
// 显示按键信息
keyInfo.textContent = `KeyDown: ${e.key} (${e.keyCode})`;
// Ctrl+S 保存
if (e.ctrlKey && e.key === 's') {
e.preventDefault(); // 阻止浏览器默认保存
console.log('Ctrl+S 被按下 - 执行保存操作');
}
// ESC键
if (e.key === 'Escape') {
console.log('ESC键按下');
}
});
// keyup - 按键释放时触发
document.addEventListener('keyup', function(e) {
console.log('按键释放:', e.key);
setTimeout(() => {
keyInfo.textContent = '等待按键...';
}, 1000);
});
})();
// ==UserScript==
// @name 键盘事件示例
// @namespace http://tampermonkey.net/
// @version 1.0
// @description 学习键盘事件监听
// @match *://*/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
let keyInfo = document.createElement('div');
keyInfo.style.cssText = `
position: fixed;
top: 10px;
right: 10px;
background: #333;
color: white;
padding: 10px;
border-radius: 5px;
z-index: 10000;
font-family: monospace;
`;
document.body.appendChild(keyInfo);
// keydown - 按键按下时触发
document.addEventListener('keydown', function(e) {
console.log('按键按下:', e.key, 'KeyCode:', e.keyCode);
// 显示按键信息
keyInfo.textContent = `KeyDown: ${e.key} (${e.keyCode})`;
// Ctrl+S 保存
if (e.ctrlKey && e.key === 's') {
e.preventDefault(); // 阻止浏览器默认保存
console.log('Ctrl+S 被按下 - 执行保存操作');
}
// ESC键
if (e.key === 'Escape') {
console.log('ESC键按下');
}
});
// keyup - 按键释放时触发
document.addEventListener('keyup', function(e) {
console.log('按键释放:', e.key);
setTimeout(() => {
keyInfo.textContent = '等待按键...';
}, 1000);
});
})();
// ==UserScript==
// @name 自定义界面示例
// @namespace http://tampermonkey.net/
// @version 1.0
// @description 学习创建自定义按钮和面板
// @match *://*/*
// @grant none
// ==/UserScript==(function() {'use strict';// 创建自定义按钮const customBtn = document.createElement('button');customBtn.textContent = '打开面板';customBtn.style.cssText = `position: fixed;top: 10px;left: 10px;z-index: 10000;padding: 10px 15px;background: #28a745;color: white;border: none;border-radius: 5px;cursor: pointer;font-size: 14px;`;// 创建自定义面板const panel = document.createElement('div');panel.style.cssText = `position: fixed;top: 50px;left: 10px;background: white;border: 2px solid #28a745;border-radius: 8px;padding: 15px;z-index: 10000;display: none;box-shadow: 0 4px 12px rgba(0,0,0,0.1);min-width: 200px;`;panel.innerHTML = `<h3 style="margin:0 0 10px 0; color: #28a745;">自定义面板</h3><p>这是一个通过JavaScript创建的自定义面板</p><button id="panelBtn">面板按钮</button><button id="closePanel">关闭</button>`;document.body.appendChild(customBtn);document.body.appendChild(panel);// 按钮点击显示面板customBtn.addEventListener('click', function() {if (panel.style.display === 'none') {panel.style.display = 'block';} else {panel.style.display = 'none';}});// 面板内按钮事件panel.querySelector('#panelBtn').addEventListener('click', function() {alert('面板按钮被点击了!');});// 关闭面板panel.querySelector('#closePanel').addEventListener('click', function() {panel.style.display = 'none';});
})();// ==UserScript==
// @name 右键菜单示例
// @namespace http://tampermonkey.net/
// @version 1.0
// @description 学习创建自定义右键菜单
// @match *://*/*
// @grant none
// ==/UserScript==(function() {
'use strict';
// 创建自定义右键菜单
const contextMenu = document.createElement('div');
contextMenu.style.cssText = `
position: fixed;
background: white;
border: 1px solid #ccc;
border-radius: 5px;
padding: 5px 0;
z-index: 10000;
display: none;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
min-width: 150px;
`;
contextMenu.innerHTML = `
<div class="menu-item" data-action="search">搜索选中文本</div>
<div class="menu-item" data-action="copy">复制文本</div>
<div class="menu-item" data-action="refresh">刷新页面</div>
`;
// 菜单项样式
const style = document.createElement('style');
style.textContent = `
.menu-item {
padding: 8px 15px;
cursor: pointer;
font-size: 14px;
}
.menu-item:hover {
background: #f0f0f0;
}
`;
document.head.appendChild(style);
document.body.appendChild(contextMenu);
let selectedText = '';
// 监听文本选择
document.addEventListener('selectionchange', function() {
selectedText = window.getSelection().toString().trim();
});
// 右键点击显示菜单
document.addEventListener('contextmenu', function(e) {
e.preventDefault(); // 阻止默认右键菜单
// 设置菜单位置
contextMenu.style.left = e.pageX + 'px';
contextMenu.style.top = e.pageY + 'px';
contextMenu.style.display = 'block';
});
// 点击其他地方隐藏菜单
document.addEventListener('click', function() {
contextMenu.style.display = 'none';
});
// 菜单项点击事件
contextMenu.addEventListener('click', function(e) {
const action = e.target.getAttribute('data-action');
switch(action) {
case 'search':
if (selectedText) {
window.open(`https://www.google.com/search?q=${encodeURIComponent(selectedText)}`, '_blank');
}
break;
case 'copy':
if (selectedText) {
navigator.clipboard.writeText(selectedText);
alert('文本已复制: ' + selectedText);
}
break;
case 'refresh':
location.reload();
break;
}
contextMenu.style.display = 'none';
});
})();
拖拽
// ==UserScript==
// @name 拖拽操作示例
// @namespace http://tampermonkey.net/
// @version 1.0
// @description 学习拖拽操作
// @match *://*/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
// 创建可拖拽元素
const draggable = document.createElement('div');
draggable.textContent = '拖拽我';
draggable.style.cssText = `
position: fixed;
top: 50px;
right: 50px;
width: 100px;
height: 100px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
display: flex;
align-items: center;
justify-content: center;
border-radius: 10px;
cursor: move;
z-index: 10000;
user-select: none;
box-shadow: 0 4px 15px rgba(0,0,0,0.2);
`;
// 创建放置区域
const dropZone = document.createElement('div');
dropZone.textContent = '放置到这里';
dropZone.style.cssText = `
position: fixed;
top: 50px;
left: 50px;
width: 200px;
height: 200px;
border: 3px dashed #667eea;
border-radius: 10px;
display: flex;
align-items: center;
justify-content: center;
background: rgba(102, 126, 234, 0.1);
z-index: 9999;
`;
document.body.appendChild(draggable);
document.body.appendChild(dropZone);
// 设置元素可拖拽
draggable.draggable = true;
// 拖拽开始
draggable.addEventListener('dragstart', function(e) {
e.dataTransfer.setData('text/plain', 'draggable-element');
e.target.style.opacity = '0.5';
console.log('拖拽开始');
});
// 拖拽结束
draggable.addEventListener('dragend', function(e) {
e.target.style.opacity = '1';
console.log('拖拽结束');
});
// 在放置区域上时
dropZone.addEventListener('dragover', function(e) {
e.preventDefault(); // 必须阻止默认行为才能放置
e.target.style.background = 'rgba(102, 126, 234, 0.3)';
});
// 离开放置区域
dropZone.addEventListener('dragleave', function(e) {
e.target.style.background = 'rgba(102, 126, 234, 0.1)';
});
// 放置
dropZone.addEventListener('drop', function(e) {
e.preventDefault();
e.target.style.background = 'rgba(102, 126, 234, 0.1)';
// 移动元素到放置区域
e.target.appendChild(draggable);
draggable.style.position = 'static';
console.log('元素已放置');
});
})();
