如何使标题转换器与许多兼容?

时间:2016-07-10 11:06:38

标签: javascript jquery html

好吧,我有一个标题更改器,所以如果视口中的分区或元素可见,标题将根据分区中的标题属性而改变。问题是它只与ONE部门兼容。它没有用,或者与许多部门不兼容。

For Live Testing/Viewing
jsFiddle - For Viewing of Codes

我的Javascript代码:

SELECT distinct record_id, record_type, second_record_id, second_record_type 
FROM closure 
WHERE ( record_id=1 OR second_record_id = 1 )
AND ( record_type="files" OR second_record_type="files" ) 

我的HTML正文代码:

// Viewport Configuration - Please don't edit this!
$.fn.is_on_screen = function(){
    var win = $(window);
    var viewport = {
        top : win.scrollTop(),
        left : win.scrollLeft()
    };
    viewport.right = viewport.left + win.width();
    viewport.bottom = viewport.top + win.height();

    var bounds = this.offset();
    bounds.right = bounds.left + this.outerWidth();
    bounds.bottom = bounds.top + this.outerHeight();

    return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
};
// End Viewport Configuraton

// This is the main config of the checkpage.js -- Feel free to edit it into your own config
if( $('.target').length > 0 ) { // If the target element exists
    if( $('.target').is_on_screen() ) { // Show this if the target element is existing after loading the DOM
      document.title = $('.target')[0].title; // This shows the target title attribute if it visible
    } else {
        document.title = "Prospekt | A Gaming Community"; // Show this if the element isn't in the Viewport
    }
}
$(window).scroll(function(){ // Bind Windows Scroll Event
    if( $('.target').length > 0 ) { // Show this if the element exists in DOM
        if( $('.target').is_on_screen() ) { // Show this if the element is visible to DOM
            document.title = $('.target')[0].title; // This shows the target title attribute if it visible
        } else {
        document.title = "Prospekt | A Gaming Community"; // If the article isn't there, change the title to default
        }
    }
});
// End Main Config

1 个答案:

答案 0 :(得分:0)

首先,您当前的实现使得无法动态更改标题,因为您始终将标题设置为$('.target')[0].title,这将始终从对象列表的第一个节点获取标题(是的,在这种情况下,$('.target')返回的元素多于元素。此外,您只需检查屏幕上是否有第一个div并忽略所有其他屏幕。

你需要做的是遍历所有找到的元素并检查每个元素,是否在屏幕上,在屏幕上的第一个停止,或者如果屏幕上没有一个,则返回默认标题

示例:

$(window).scroll(function(){ // Bind Windows Scroll Event
    if( $('.target').length > 0 ) { // Run this if we have at least one target element
        $('.target').each(function() { //Check eac
            if( $(this).is_on_screen() ) { // Check if the element is visible to the user
                document.title = $(this)[0].title; // Show the target title attribute
            }
        });
    }
});

请注意,这个例子缺少我上面提到的检查,只是粗略地了解它是如何完成的。