javascript - 如何让 jQuery show() 停留在页面上

标签 javascript jquery css dom

我有两个相邻的表格,右边的表格在使用 show() 时出现了 div 在页面外显示的问题。

我怎样才能避免这种情况?

    $("tr.invoice_head td:last-child a").hover(
        function(){$(".custNotes-span",this).position({
            of: '.custNotes-span',
            my: 'right top',
            at: 'right top',
            offset: '.custNotes-span'
        }).css({
            'z-index':'100',
            'width': '200px',
            'position':'absolute'}).show();},
        function(){$(".custNotes-span").hide();}
    );

更新:JSFiddle 链接 - http://jsfiddle.net/r60ywb0L/2/

抱歉,这是 JSFiddle 的副本,包括使用的 JS 和 CSS。有两个表格彼此相邻 float ,当我将鼠标悬停在 tr.invoice_head 的最后一个 td 内的锚定链接上时,我试图让 div.custNotes-span 显示在页面的其余部分。

最佳答案

在 fiddle 中玩耍,我发现:

  • 需要在定位前应用 CSS。
  • 元素需要在定位时呈现在 DOM 中(但不一定“可见”)。
  • position() 映射的of 属性最好设置为最近的表格行
  • collision:'fit' 似乎比默认的 collision:'flip' 效果更好,尽管您可能不会注意到除了 fiddle 之外的区别。
  • 元素可以定位一次。无需在每次放映时重新定位它们。

以下解决方法利用 CSS visibility 允许正确定位,同时避免 FOUC。

  • 应用 .css() 包括 visibility:hidden
  • 使用 .show()“显示”(但仍然隐藏)
  • 应用.position()
  • .hide()隐藏
  • 使用 visibility:visible 使“可见”(但仍然隐藏)

然后可以在悬停处理程序中使用 .show().hide() 显示/隐藏元素。

// As the positioning map and the css map get used in a loop, it's worth assigning them outside the loop.
var maps = {
    css: {
        'z-index': '100',
        'width': '200px',
        'position': 'absolute',
        'visibility': 'hidden'
    },
    pos: {
        'of': null, //added dynamically below
        'my': 'right top',
        'at': 'right top',
        'collision': 'fit'
    }
};

//Apply CSS and pre-position the notes
$(".custNotes-span").each(function() {
    $(this)
        .css(maps.css)
        .show()
        .position( $.extend({}, maps.pos, {'of': $(this).closest("tr")}) )
        .hide()
        .css('visibility','visible');
});

//The maps have done their work and can be deleted from the closure.
delete maps.css;
delete maps.pos;

//Hover actions
$(".custNotes a").hover(function() {
    $(".custNotes-span", this).show();
}, function() {
    $(".custNotes-span", this).hide();
});

选择器被修改为更加友好。

DEMO

关于javascript - 如何让 jQuery show() 停留在页面上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26498313/

相关文章:

javascript - Hbase:使用JSON同时放置一行的多个版本

javascript - 如何用 jQuery 1.8.3 的实现替换 jQuery 1.9.1 的 $.parseJSON 函数

css - 使用 CSS 为图像添加圆 Angular

javascript - 使用字符串插值进行函数调用

javascript - Babylon.js 和 Ember : Ember addon with prototype extensions disabled within an app with prototype extensions enabled?

javascript - 定位jquery ui对话框

javascript - JS如何在使用ajax后获取嵌入元素的值

javascript - 加载另一个 div 后显示一个 div

css - 尽管内部 div 宽度大于 100%,但将内部 div 保持在同一行

javascript - 如何测试呈现 View 的 Express Routes