JavaScript_采用CSS内联样式模拟工具提示;

本文介绍了一种使用纯CSS和JavaScript创建工具提示的方法。通过自定义的Tooltip类,可以在鼠标悬停时显示选中文本的内容,并在2秒后自动隐藏。此方法适用于网页中需要临时展示额外信息的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

=>实现功能:采用JS事件驱动以及CSS内联样式模拟工具提示;

<html>

    <head>
        <title>使用CSS的工具提示</title>
        <script type="text/javascript">
            function Tooltip() {
                this.tooltip = document.createElement("div");
                this.tooltip.style.position = "absolute";
                this.tooltip.style.width = "250px";
                this.tooltip.style.height = "150px";
                this.tooltip.style.backgroundColor = "lightgray";
                this.tooltip.style.border = "3px outset black";
                this.tooltip.style.visibility = "visible";
                this.tooltip.id = "tooltip";
                this.tooltip.className = "tooltipShadow";

                this.content = document.createElement("div");
                this.content.style.position = "relative";
                this.content.id = "tipContent";
                this.content.className = "tooltipContent";

                this.tooltip.appendChild(this.content);

                console.log("Tooltip类");
            }
            Tooltip.prototype.show = function(text, x, y) {
                this.content.innerHTML = text;
                this.tooltip.style.left = x + "px";
                this.tooltip.style.top = y + "px";
                this.tooltip.style.visibility = "visible";

                if(this.tooltip.parentNode != document.body) {
                    document.body.appendChild(this.tooltip);
                }
        
                console.log("Tooltip show方法");
            }
            Tooltip.prototype.hide = function() {
                this.tooltip.style.visibility = "hidden";
                
                console.log("Tooltip hide方法");
            }

            function fireFn() {
                // 获取用户选择的文本
                var text = "";
                if(window.getSelection) {
                    text = window.getSelection().toString();
                }else if(document.getSelection) {
                    text = document.getSelection();
                }else if(document.selection) {
                    text = document.selection.createRange().text;
                }

                var tip = new Tooltip();
                tip.show(text, 100, 100);
                setTimeout(function() {
                    tip.hide();
                }, 2000);
            }
        </script>
    </head>
    <body>
        <p onmouseup="fireFn()">好多即将做软件的或做的时间不长的同仁大多时候关注的是新技术,是创造性;但就和阳光下总有阴影一样,
        不管方法如何更迭,总有些东西无法彻底改善。</p>
    </body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值