js实现对联
实现对联效果(JavaScript)
方法一:使用绝对定位与动态生成
通过JavaScript动态生成对联元素并设置绝对定位,使其固定在页面两侧。
// 创建对联元素
const leftCouplet = document.createElement('div');
leftCouplet.innerHTML = '上联内容';
leftCouplet.style.position = 'fixed';
leftCouplet.style.left = '10px';
leftCouplet.style.top = '50%';
leftCouplet.style.transform = 'translateY(-50%)';
const rightCouplet = document.createElement('div');
rightCouplet.innerHTML = '下联内容';
rightCouplet.style.position = 'fixed';
rightCouplet.style.right = '10px';
rightCouplet.style.top = '50%';
rightCouplet.style.transform = 'translateY(-50%)';
// 添加到页面
document.body.appendChild(leftCouplet);
document.body.appendChild(rightCouplet);
方法二:响应式布局适配
结合CSS媒体查询与JavaScript,实现不同屏幕尺寸下的对联显示优化。

function adjustCouplet() {
const screenWidth = window.innerWidth;
if (screenWidth < 768) {
leftCouplet.style.display = 'none';
rightCouplet.style.display = 'none';
} else {
leftCouplet.style.display = 'block';
rightCouplet.style.display = 'block';
}
}
window.addEventListener('resize', adjustCouplet);
adjustCouplet(); // 初始化调用
方法三:添加关闭功能
为对联增加关闭按钮,提升用户体验。

const closeBtnLeft = document.createElement('span');
closeBtnLeft.innerHTML = '×';
closeBtnLeft.style.cursor = 'pointer';
closeBtnLeft.onclick = () => leftCouplet.remove();
const closeBtnRight = document.createElement('span');
closeBtnRight.innerHTML = '×';
closeBtnRight.style.cursor = 'pointer';
closeBtnRight.onclick = () => rightCouplet.remove();
leftCouplet.prepend(closeBtnLeft);
rightCouplet.prepend(closeBtnRight);
方法四:动画效果增强
使用CSS动画或JavaScript实现对联的入场效果。
leftCouplet.style.transition = 'opacity 0.5s, transform 0.5s';
rightCouplet.style.transition = 'opacity 0.5s, transform 0.5s';
leftCouplet.style.opacity = '0';
rightCouplet.style.opacity = '0';
setTimeout(() => {
leftCouplet.style.opacity = '1';
rightCouplet.style.opacity = '1';
}, 100);
方法五:内容动态加载
通过API或本地数据动态加载对联内容。
fetch('couplet-api-url')
.then(response => response.json())
.then(data => {
leftCouplet.innerHTML = data.left;
rightCouplet.innerHTML = data.right;
});
注意事项
- 对联内容应考虑文化适配性
- 移动端需谨慎使用固定定位元素
- 关闭功能应明确可见
- 动画效果不宜过于复杂影响性能






