希望有一个可以随着浏览器窗口调整大小/缩放/拉伸的背景。
尽管似乎有一种 CSS3 方法,但它并未得到广泛支持。似乎有许多 JQuery 方法——但它们都有点......好吧,看起来有点笨拙或需要太多手动输入。
所以......我在想......一些能够学习基础知识并为我们完成大部分工作的东西怎么样?
以下是我到目前为止所得到的:
它基于一些现有的方法,如Fullscreenr,并进行了一些修改。
<script type="text/javascript">
//<![CDATA[
$.fn.fullscreenr = function(options) {
var defaults = { width: 1280, height: 1024, bgID: 'bgimg' };
var options = $.extend({}, defaults, options);
$(document).ready(function() {
$(options.bgID).fullscreenrResizer(options);
});
$(window).bind("resize", function() {
$(options.bgID).fullscreenrResizer(options);
});
return this;
};
$.fn.fullscreenrResizer = function(options) {
// Set bg size
var ratio = options.height / options.width;
// Get browser window size
var browserwidth = $(window).width();
var browserheight = $(window).height();
// Scale the image
if ((browserheight/browserwidth) > ratio){
$(this).height(browserheight);
$(this).width(browserheight / ratio);
} else {
$(this).width(browserwidth);
$(this).height(browserwidth * ratio);
}
// Center the image
$(this).css('left', (browserwidth - $(this).width())/2);
$(this).css('top', (browserheight - $(this).height())/2);
return this;
};
$(document).ready(function() {
// Get the URL based on the Background property
function extractUrl(input) {
return input.replace(/"/g,"").replace(/url\(|\)$/ig, "");
}
// Get the Background CSS Property.
imageURL = extractUrl($("body").css("background-image"));
$('body').prepend('<div id="triquiback"></div');
$('#triquiback').prepend('<img id="triquibackimg" src="'+imageURL+'" />');
var triquibackcss = {
'left' : '0',
'top' : '0',
'position' : 'fixed',
'overflow' : 'hidden',
'zIndex' : '-9999'
};
var triquibackimgcss = {
'position' : 'fixed'
};
$("#triquiback").css(triquibackcss);
$("#triquibackimg").css(triquibackimgcss);
});
$(window).load(function() {
var pic = $('img');
pic.removeAttr("width");
pic.removeAttr("height");
thiswidth = pic.width();
thisheight = pic.height();
// You need to specify the size of your background image here
// (could be done automatically by some PHP code)
var FullscreenrOptions = {
width : thiswidth,
height : thisheight,
bgID : 'img'
};
// This will activate the full screen background!
jQuery.fn.fullscreenr(FullscreenrOptions);
});
//]]>
</script>
那么......我做了哪些改变?
好吧,我设法做到了,这样您就不必指定背景图像/文件,它会自动从正文中提取它。
我还设法使它可以自己检测高度/宽度。
此外 - 我这样做是为了通过 JQuery 插入要调整大小的包装器和图像,而不是包含在标记中,并且它也通过 JS 设置样式。
现在......问题/愿望?
好吧 - 对于初学者来说 - 这一切都在主要的 html 文档中。
我希望它作为外部文件,但我尝试的一切都失败了!可能是由于对其进行了hackjob。
在那之后 - 是否有可能使我们可以指定它要应用于的元素(以防我们想要除了 body 以外的东西)?
一般来说 - 它看起来像一团糟,(由于 hackjob 的错误混搭),我很确定它该死的低效/不整洁。有没有更好的方法来编写代码?
我不是 100% 确定,但也许 z-index 属性应该是可设置的!因为我想在某些时候可能有人可能有不同的设置并希望有不同的价值?
(包括默认值以防未指定?)
IE6 ...我想我错过了如何使CSS适用于IE6,如果它是IE6,是否可以识别浏览器并提供不同的样式?
除此之外,它似乎运行良好。调整窗口大小,适用于 FF3/最新的 chrome (6?)、IE7 等。
我已经看到了一个测试是否支持 CSS3 的小技巧,所以我还将测试是否可以使用它来检测是否需要这样做(如果不需要,应该可以节省一些臃肿)。
+
我觉得很厚颜无耻寻求帮助...
我已经习惯自己做这种事情,但是浪费一整天做某事似乎很愚蠢,因为有更聪明/更好的人可以帮助发现常见问题并让我把那一天变成一周的头发拉扯: D
所以提前(如果我幸运的话)谢谢你。