창 크기를 조정할 때 JQuery 도구 설명을 다시 가운데로 조정
-
07-07-2019 - |
문제
텍스트 상자 바로 위에 툴팁을 배치하는 함수를 작성했습니다.
이 함수는 두 가지 인수를 사용합니다.
텍스트 상자 ID - 툴팁이 표시될 텍스트 상자의 ID입니다.
- 예: "#텍스트박스A"
- 예: "#텍스트박스A"
도구 팁 ID - 텍스트 상자 위에 표시될 툴팁의 ID입니다.
- 예: "#toolTipA"
function positionTooltip(textBoxId, toolTipId){
var hoverElementOffsetLeft = $(textBoxId).offset().left;
var hoverElementOffsetWidth = $(textBoxId)[0].offsetWidth;
var toolTipElementOffsetLeft = $(toolTipId).offset().left;
var toolTipElementOffsetWidth = $(toolTipId)[0].offsetWidth;
// calcluate the x coordinate of the center of the hover element.
var hoverElementCenterX =
hoverElementOffsetLeft + (hoverElementOffsetWidth / 2);
// calculate half the width of the toolTipElement
var toolTipElementHalfWidth = toolTipElementOffsetWidth / 2;
var toolTipElementLeft = hoverElementCenterX - toolTipElementHalfWidth;
$(toolTipId)[0].style.left = toolTipElementLeft + "px";
var toolTipElementHeight = $(toolTipId)[0].offsetHeight;
var hoverElementOffsetTop = $(textBoxId).offset().top;
var toolTipYCoord = hoverElementOffsetTop - toolTipElementHeight;
toolTipYCoord = toolTipYCoord - 10;
$(toolTipId)[0].style.top = toolTipYCoord + "px";
$(toolTipId).hide();
$(textBoxId).hover(
function(){ $(toolTipId + ':hidden').fadeIn(); },
function(){ $(toolTipId + ':visible').fadeOut(); }
);
$(textBoxId).focus (
function(){ $(toolTipId + ':hidden').fadeIn(); }
);
$(textBoxId).blur (
function(){ $(toolTipId+ ':visible').fadeOut(); }
);
}
이 기능은 초기 페이지 로드 시 제대로 작동합니다.
그러나 사용자가 창 크기를 조정한 후에는 도구 설명이 관련 텍스트 상자 위에 더 이상 표시되지 않는 위치로 이동합니다.
창 크기가 조정될 때 positionTooltip() 함수를 호출하여 문제를 해결하기 위해 몇 가지 코드를 작성해 보았지만 어떤 이유로 페이지가 로드될 때처럼 도구 설명의 위치가 변경되지 않습니다.
var _resize_timer = null;
$(window).resize(function() {
if (_resize_timer) {clearTimeout(_resize_timer);}
_resize_timer = setTimeout(function(){
positionTooltip('#textBoxA', ('#toolTipA'));
}, 1000);
});
크기 조정 후 페이지가 처음 로드되었을 때처럼 도구 설명의 위치를 올바르게 변경하지 않는 이유가 무엇인지 정말 이해가 안 됩니다.
해결책
도구 설명의 위치를 계산하는 논리는 처음에 positionTooltip을 호출할 때만 실행됩니다.fadeIn 호출 전에 위치를 다시 계산하기 위해 호출하려고 합니다.
다른 팁
Settimeout ()을 사용하여 기능을 시작하는 이유를 이해하지 못합니다. 노력하다
$(function(){
// all your code onDocumentReady
...
...
$(window).resize(function() {
positionTooltip('#textBoxA', ('#toolTipA'));
});
});
그것은 나에게 매력처럼 작동했습니다. 유일한 단점은 때때로 X, Y 위치를 얻지 못하는 것입니다. 분명히 객체의 패딩/마진 값으로 보상하는 것이 아니라는 것입니다. 같은 설정 :
toolTipElementLeft = toolTipElementLeft + 40;
$(toolTipId)[0].style.left = toolTipElementLeft + "px";
그리고
toolTipYCoord = toolTipYCoord + 25;
$(toolTipId)[0].style.top = toolTipYCoord + "px";
제휴하지 않습니다 StackOverflow