简体   繁体   中英

How to align the center of the tooltip

How to arrange a pop-up tooltip at the center when you hover? Tooltip inserted via script, absolutely positioned relative to the block.

JavaScript code:

elem.style.width = target.clientWidth / 2 + 'px';
elem.style.top = target.clientHeight / 2 - div.offsetHeight + 'px';
elem.style.left = target.clientWidth / 2 - div.offsetWidth + 'px'; 

JavaScript

Fiddle

You are subtracting the whole height of the appended div rather than just half:

document.addEventListener('mouseover', function(e) {
    var target = e.target;
    if(target.className != 'd1') return;
    var header = target.getElementsByTagName('h2')[0].innerHTML;
    var content = target.getElementsByTagName('p')[0].innerHTML;

    var div = document.createElement('div');
    div.className = 'tooltip';
    div.insertAdjacentHTML('beforeEnd', "<h2>" + header +"</h2>");
    div.insertAdjacentHTML('beforeEnd', "<p>" + content +"</p>");
    target.appendChild(div);

    div.style.width = target.clientWidth / 2 + 'px';
    div.style.top = ((target.clientHeight / 2) - (div.offsetHeight/2)) + 'px';
    div.style.left = ((target.clientWidth / 2) - (div.offsetWidth/2)) + 'px';  

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM