html点击按钮弹出悬浮窗_JS点击出现悬浮窗效果详解

Demo

window.onload = function(){

var btn = document.getElementsByTagName('button')[0];

var flt = document.getElementsByTagName('div')[0];

btn.onclick = function(){

event.cancelBubble = true;

var x = btn.offsetLeft - 15 + 'px';

var y = btn.offsetTop - 100 + 'px';

flt.style.top = y;

flt.style.left = x;

flt.style.display = 'block';

}

document.onclick = function(){

flt.style.display = 'none';

}

}

*{

margin: 0px;

padding: 0px;

}

div{

width: 60px;

height: 100px;

background: #33ccff;

display: none;

position: absolute;

}

div ul{

text-align: center;

}

div li{

list-style-type: none;

}

button{

top: 300px;

left: 400px;

position: absolute;

}

Click

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以通过以下步骤使用 JavaScript 实现可拖动悬浮按钮效果: 1. 创建一个 HTML 页面,并添加一个按钮元素。你可以使用以下代码: ```html <button id="floating-button">悬浮按钮</button> ``` 2. 在 CSS 中设置按钮元素的样式,使其看起来像一个悬浮按钮。你可以使用以下代码: ```css #floating-button { position: fixed; bottom: 20px; right: 20px; width: 50px; height: 50px; background-color: #4285f4; color: #fff; border-radius: 50%; border: none; outline: none; cursor: move; } ``` 3. 在 JavaScript 中添加事件监听器,以便在用户单击按钮时启动拖动功能。你可以使用以下代码: ```javascript // 获取悬浮按钮元素 const floatingButton = document.getElementById('floating-button'); // 定义变量,用于存储鼠标按下时的坐标 let startX, startY; // 添加鼠标按下事件监听器 floatingButton.addEventListener('mousedown', function(e) { // 记录鼠标按下时的坐标 startX = e.clientX; startY = e.clientY; // 添加鼠标移动事件监听器 document.addEventListener('mousemove', moveButton); }); // 添加鼠标松开事件监听器 document.addEventListener('mouseup', function() { // 移除鼠标移动事件监听器 document.removeEventListener('mousemove', moveButton); }); // 定义函数,用于移动悬浮按钮 function moveButton(e) { // 计算鼠标移动的距离 const deltaX = e.clientX - startX; const deltaY = e.clientY - startY; // 获取悬浮按钮的当前位置 const buttonPosition = floatingButton.getBoundingClientRect(); // 移动悬浮按钮到新的位置 floatingButton.style.left = buttonPosition.left + deltaX + 'px'; floatingButton.style.top = buttonPosition.top + deltaY + 'px'; // 更新鼠标按下时的坐标 startX = e.clientX; startY = e.clientY; } ``` 以上代码通过添加鼠标事件监听器,实现了当用户按下鼠标左键时,悬浮按钮可以跟随鼠标移动。你可以根据需要修改样式和位置参数,以适应你的代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值