javascript - 点击位置 <div> 标签

标签 javascript jquery html css

我一直在尝试定位 <div>我点击的元素。

这是我要定位的div

<main class="">
    <div class="overlay"></div>
    @Html.Raw(ViewBag.Breadcrumb)
    <div class="split">
        <div class="half">
            <div class="section-head">
                <i class="section-icon fa fa-calendar"></i>
                <h2>mon Calendrier</h2>
                <small>Dates à retenir</small>
            </div>
            <div class="calendar-container">
                <!-- CALENDAR -->
                <div class="action-calendar"></div>
                <!-- TOOLTIP -->
                <div class="tooltip-wrapper">
                    <div class = "day-event">
                        <span class="title"></span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

这与日历上的事件绑定(bind)(如果我有一个日期与事件关联)。 我想要获得的是,只要我点击一个日期,我就想要这个 <div>放置在鼠标点击的位置。

在我寻找可以帮助我的东西时发现了这个 [ How do I position a div next to a mouse click using JQuery?但这对我没有帮助。 div 正在改变位置,但甚至没有靠近我点击的位置。

这是应该实现的代码:

var tooltip_HTML = $(".day-event .title").html();
var position = $(".action-calendar a.ui-state-active").parent().offset();
$(".tooltip-wrapper").css({ top: position.top, left: position.left })

CSS

.tooltip-wrapper .title{
    color:#ffffff; 
    font-family:'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
}

.tooltip-wrapper{
    position: absolute; 
    z-index: 2000;
    width: 100%
}

.tooltip-wrapper .day-event {
    background: #000000; 
    position: relative; 
    width:250px;
    color: #FFFFFF;
    /*height: 100px;*/ 
    line-height: 20px;
    text-align: center;  
    border-radius: 10px;
    opacity: 0.9;
    filter: Alpha(opacity=90);
    z-index: 10000;
}

.tooltip-wrapper span:after {
  content: '';
  position: absolute;
  bottom: 100%;
  left: 50%;
  margin-left: -8px;
  width: 0; 
  height: 0;
  border-bottom: 8px solid #000000;
  border-right: 8px solid transparent;
  border-left: 8px solid transparent;
}

问题是它改变了位置,但没有改变它假设的位置。

谢谢。

最佳答案

event.pageXevent.pageY获取鼠标相对于页面最左上部分的水平和垂直位置。当你设置 position: absolute .它的顶部和左侧值将根据它的相对父容器设置。

因此您得到了错误的坐标。 要解决此问题,您必须在 <body> 之后设置父容器。并将其设置为 width: 100%;设置父容器 position: relative; .现在因为你已经有了整个页面的宽度和高度,event.pageXevent.pageY将为您提供 top 的正确坐标和 left职位

关于javascript - 点击位置 <div> 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38132937/

相关文章:

javascript - 无法将js加载到MongoDB中

javascript - 覆盖 Kendo UI 中的 javascript 函数

javascript - 在用户完成输入而不是输入每个字符后,如何获取用户的输入?

java - 如何在不影响其css和js的情况下在现有jsp文件上应用struts2标签

javascript - 为什么这个 jQuery 输入值检查器不起作用?

javascript - 获取生成的隐藏字段的值

jquery - 如何阻止元素在移动设备上调整大小?

javascript - 更改按钮的背景颜色

javascript - 将文件转换为数组并使用数据列表和选项标签添加数组元素以用于自动完成文本框

javascript - 被屏蔽的 HTML 视频元素源无法触发错误事件