【问题标题】:Keep div follow cursor in specific div parent让 div 跟随光标在特定的 div 父级中
【发布时间】:2021-11-30 04:52:47
【问题描述】:

如何在其父 div ($(this)) 中制作弹出跟随光标? 我试过这个,但是每次当我悬停一个元素时它的位置发生变化时,popin 都不会跟随光标。

const $divs = $(".domtom-container .svg-container");
let dept = {}, total = {};
$divs.each(function (i) {
    var popup_topo = $("<div class='popup_topo'>" + dept + "<br/>" + total + " parrainages</div>");
    
    $(this).on('mousemove', function (event) {
     const x = event.clientX;
      const y = event.clientY;

      $(this).append(popup_topo);
      popup_topo.css({
        top: `${y}px`,
        lef: `${x}px`,
      });
    }).on('mouseleave', function (event) {
      popup_topo.remove();
    });
});

HTML:

 <div class="domtom-container">
   <div class="svg-container svg-topo">
      <svg width="36" height="43"> </svg>
      <p> Nouvelle-Calédonie </p>
   </div>
   <div class="svg-container svg-topo">
      <svg width="52" height="65"></svg>
      <p> Guyane </p>
   </div>
   <div class="svg-container svg-topo">
      <svg width="68" height="44"> </svg>

      <p> Polynésie française </p>
   </div>
   <div class="svg-container">
      <svg width="48" height="37"> </svg>
      <p> Parlement européen </p>
   </div>
   <div class="svg-container svg-topo">
      <svg width="51" height="45"></svg>
      <p> La Réunion </p>
   </div>
</div>

CSS:

.svg-container {
        &.svg-topo {
            position: relative;
            .popup_topo {
                position: absolute;
                font-size: 1.4rem;
                background-color: #1E2382;
                color: #FFF;
                padding: .5rem;
                transition: .1s;
                transform: translate(-50%, -50%);
                z-index: 999;
            }
            &:hover {
                svg {
                    path {
                        fill : #1E2382!important;
                    }
                }
            }
            svg {
                min-height: 5rem;
            }
        }
    }

我认为popin位置的计算做得不好,但我不知道如何。 请检查下面的屏幕截图(GIF)

PS:我正在使用 Datamaps 插件:https://github.com/markmarkoh/datamaps/blob/master/README.md#using-custom-maps

【问题讨论】:

  • popup_topo 的 CSS 是什么? $(this) 是什么元素?
  • 请提供您的代码Minimal, Reproducible Example。另外,你的问题不是很清楚。
  • @epascarello,我更新了我的帖子
  • @Rojo,把所有的代码都放出来不容易,因为它来自插件,我尽力了(更新后):/
  • 您将 div 附加到 svg-topo div,但位置基于页面,而不是 svg-topo div。您需要将弹出窗口附加到 div 或调整 x/y 位置,使其基于悬停元素而不是页面的顶部。

标签: javascript jquery mousemove


【解决方案1】:

这是因为 clientX 和 ClientY 是根据 SVG 元素的位置计算的。你想要的是屏幕上的绝对点。

考虑,

const $divs = $(".domtom-container .svg-container");
const x = $divs.offset().left - event.clientX;
const y = $divs.offset().top - event.clientY;

now pass this value to the css.
 popup_topo.css({
        top: `${y}px`,
        lef: `${x}px`,
      });

【讨论】:

  • 这不起作用,我在 DOM 中有 popin,但我没有在旁边看到它。
猜你喜欢
  • 1970-01-01
  • 2011-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-06
相关资源
最近更新 更多