javascript - JQuery - 相对于按钮定位弹出窗口

标签 javascript jquery html css

我正在尝试相对于其按钮或使用 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');

 });

jsFiddle

最佳答案

创建一个单独的函数来显示问题,它将点击的按钮和问题作为参数:

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>'
  );
});

Updated Fiddle

css left 计算可确保问题始终显示在屏幕上。

关于javascript - JQuery - 相对于按钮定位弹出窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31319823/

相关文章:

javascript - AngularJS $sce.trustAsHtml() 处理大量标记的数据

html - 在html5应用上录制音频

php - 帮助 PHP 分页

html - 使用 css 将背景图像居中时出现水平查看问题

javascript - jQuery:让第二个函数等待执行,直到第一个函数完成

javascript - 是否可以使用 JavaScript 在此 JSP 表单上进行验证?

javascript - jQuery 对象构造函数 - 调用自身的方法

javascript - 在图像上叠加 div

具有重复按钮元素的 JQuery addClass/hasClass

javascript - 获取点击按钮的值