<!DOCTYPE html>
<html>
<head>
<title>Responsive Tooltip</title>
<style>
.tooltip {
position: absolute;
display: none;
background-color: black;
color: white;
padding: 10px;
border-radius: 5px;
z-index: 1;
}
</style>
</head>
<body>
<div>
<span class="tooltip-trigger">Hover over me</span>
<div class="tooltip">This is a tooltip</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(".tooltip-trigger").mouseenter(function () {
// Get the width of the screen
var screenWidth = $(window).width();
// Get the width of the tooltip
var tooltipWidth = $(".tooltip").outerWidth();
// Get the position of the trigger element
var triggerPosition = $(this).offset();
// Calculate the position of the tooltip
var tooltipX = triggerPosition.left + ($(this).outerWidth() / 2) - (tooltipWidth / 2);
var tooltipY = triggerPosition.top - $(".tooltip").outerHeight() - 10;
// If the tooltip would go off the right side of the screen, position it on the left side of the trigger element
if (tooltipX + tooltipWidth > screenWidth) {
tooltipX = triggerPosition.left - tooltipWidth + $(this).outerWidth();
}
// If the tooltip would go off the left side of the screen, position it on the right side of the trigger element
if (tooltipX < 0) {
tooltipX = triggerPosition.left + $(this).outerWidth();
}
// If the tooltip would go off the top of the screen, position it below the trigger element
if (tooltipY < 0) {
tooltipY = triggerPosition.top + $(this).outerHeight() + 10;
}
// Set the position of the tooltip
$(".tooltip").css({
left: tooltipX,
top: tooltipY
});
// Show the tooltip
$(".tooltip").fadeIn();
});
$(".tooltip-trigger").mouseleave(function () {
// Hide the tooltip
$(".tooltip").fadeOut();
});
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<style>
.tooltip {
display: none;
position: absolute;
background-color: #333;
color: #fff;
padding: 5px 10px;
border-radius: 3px;
}
</style>
<body style="text-align:center;">
<h2>Basic Tooltip</h2>
<p>Move the mouse over the text below:</p>
<div class="tooltip-trigger" data-tooltip="#tooltip1">Trigger 1</div>
<div class="tooltip-trigger" data-tooltip="#tooltip2">Trigger 2</div>
<div class="tooltip-trigger" data-tooltip="#tooltip3">Trigger 3</div>
<div id="tooltip1" class="tooltip">Tooltip 1</div>
<div id="tooltip2" class="tooltip">Tooltip 2</div>
<div id="tooltip3" class="tooltip">Tooltip 3</div>
<p>Note that the position of the tooltip text isn't very good. Go back to the first awnser and play with code to get better positioning</p>
</body>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$('.tooltip-trigger').hover(function() {
var tooltipId = $(this).data('tooltip');
$(tooltipId).show();
}, function() {
var tooltipId = $(this).data('tooltip');
$(tooltipId).hide();
});
});
</script>
</html>
2条答案
按热度按时间1dkrff031#
nqwrtyyt2#