我正在尝试相对于其按钮或使用 jquery 单击的按钮定位弹出窗口。我想以不遮盖按钮本身的方式放置弹出窗口。将其放置在所单击按钮的左侧、右侧、上方或下方。
现在我知道我可以通过编写更多的 html 弹出窗口和 css 来做到这一点,但是必须有一种方法来动态使用一个 div 并用 jquery 定位它。我尝试使用偏移量和位置(在某一时刻),但我无法让它工作。坦率地说,我是 js 和 jquery 的入门级,所以请原谅我的菜鸟。
任何帮助将不胜感激!!
JS:
$('.trends').click(function () {
$('.questions').fadeIn();
$('.question').html('<p>What trends could potentially drive growth in the U.S.?</p>');
/* if I add this and zero out the positioning via css the pop gets offset but its way far away from this parent.
var offset = $(this).offset();
$('.questions').css('left',offset.left);
$('.questions').css('top',offset.top);*/
});
$('.consumer').click(function () {
$('.questions').fadeIn();
$('.question').html('<p>Even though we have low inflation, consumers are not increasing their spending. Why?</p>');
});
$('.industry').click(function () {
$('.questions').fadeIn();
$('.question').html('<p>What factors drove crude oil prices to fall and which industries benefited?</p>');
});
$('.henn').click(function () {
$('.questions').fadeIn();
$('.question').html('<p>MESSAGE FROM OUR PRESIDENT</p>');
var offset = $(this).offset();
$('.question').html('<p>What trends could potentially drive growth in the U.S.?</p>');
});
$('.equity').click(function () {
$('.questions').fadeIn();
$('.question').html('<p>The U.S. stock market has been rising for more than six years. What do you see ahead for equities?</p>');
});
$('.balance').click(function () {
$('.questions').fadeIn();
$('.question').html('<p>what does it look like for companies balance sheets?</p>');
});
$('.close').click(function (e) {
e.stopPropagation();
$(this).parent().hide();
$('.items').removeClass('no-effect');
});
最佳答案
创建一个单独的函数来显示问题,它将点击的按钮和问题作为参数:
function showQuestion(button, question) {
var offset = button.offset();
$('.question').html(question);
$('.questions')
.fadeIn()
.css({
left: Math.min(offset.left, $(window).innerWidth()-$('.questions').outerWidth()),
top: offset.top + button.innerHeight()
});
}
这样调用它:
$('.trends').click(function () {
showQuestion(
$(this),
'<p>What trends could potentially drive growth in the U.S.?</p>'
);
});
css
left 计算可确保问题始终显示在屏幕上。
关于javascript - JQuery - 相对于按钮定位弹出窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31319823/