JQuery - 可缩放/调整背景图像大小

发布于 2024-10-06 01:42:21 字数 3591 浏览 2 评论 0原文

我们的愿望是拥有一个可以随浏览器窗口调整大小/缩放/拉伸的背景。

尽管似乎有 CSS3 方法,但它并未得到广泛支持。 似乎有很多 JQuery 方法 - 但它们都有点......嗯,看起来有点笨重或需要太多手动输入。

所以......我在想......一些能够掌握基础知识并为我们完成大部分工作的东西怎么样?

下面是我到目前为止所得到的:

它基于一些现有的方法,例如 Fullscreenr< /a>,进行一些修改。

<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 文档中。

我希望它作为外部文件,但我尝试的一切都失败了!可能是由于对其进行了黑客攻击。

接下来 - 是否可以这样做,以便我们可以指定它要应用到的元素(如果我们想要除 body 之外的其他元素)?

一般来说,它看起来一团糟(由于黑客工作的错误混合),而且我很确定它效率低下/不整洁。有没有更好的方法来实现代码?

我不是 100% 确定,但也许 z-index 属性应该是可设置的!我认为在某些时候有人可能有不同的设置并想要不同的值?

(包括默认值,以防没有指定?)

IE6 ...我想我已经错过了如何使 CSS 适用于 IE6,如果是 IE6,是否可以识别浏览器并提供不同的样式?

抛开所有这些不谈,它似乎运作得很好。 根据窗口大小调整大小,适用于 FF3/最新的 chrome(6?)、IE7 等。

我见过一个测试 CSS3 是否受支持的小技巧, 所以我还将测试是否可以使用它来检测是否需要(如果不需要,应该节省一些膨胀)。

+

我觉得寻求帮助真是厚颜无耻...

我自己已经习惯做这种事情了,但是当有更聪明/更好的人可以做某事时,浪费一整天的时间做某事似乎很愚蠢帮助发现常见问题并避免我把这一天变成一周的拉扯:D

所以提前(如果我幸运的话)谢谢你。

The desire is to have a background that resizes/scales/stretches with the browser window.

Though there seems to be a CSS3 method, it isn't widely supported.
There seems to be numerous JQuery methods - but they all kind of ... well, seem a little clunky or require too much manual input.

So ... I was thinking ... how about something that picks up the basics and does most of it for us?

Below is what I've gotten so far:

It's based around some existing methods like Fullscreenr, with some modifications.

<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>

So ... what changes did I manage?

Well, I managed to make it so that you don't have to specify a background image/file, it picks it up automatically from the body.

I also managed to make it so that it can detect the height/width by itself.

Further - I made it so that the wrapper and image to be resized is inserted via the JQuery, rather than it being included in the markup, and that it's styled via the JS as well.

Now ... the problems/desires?

Well - for starters - this is all in the main html doc.

I'd like it as an external file, but everything I tried failed! Likely due to the hackjob done on it.

Following that - is it possible to make it so we can specify the element it is to apply to (in case we want something other than body)?

Generally - it looks like a mess, (due to the mis-mash of the hackjob), and I'm pretty sure it's damned inefficient/untidy. Is there a better way to do the code?

I'm not 100% sure, but maybe the z-index property should be settable! as I suppose it's possible that at some point someone may have a different setup and desire a different value?

(Include a default in case none is specified?)

IE6 ... I think I've missed how to make the CSS work for IE6, is it possible to identify the browser and supply different styling if it's IE6?

All that aside, it seems to work well enough.
Resizes on window resize, works in FF3/latest chrome (6?), IE7 etc.

I've seen a little trick for testing whether CSS3 is supported or not,
so I'll also test to see if I can use it to detect if this is required or not (should save some bloat if not required).

+

I feel so cheeky asking for assistance...

I'm used to doing this sort of thing myself, but seems silly to waste a whole day doing something, when there are smarter/better people that can help spot the common issues and save me turning that day into a week of hair pulling :D

So in advance (if I'm lucky) Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

爱,才寂寞 2024-10-13 01:42:21

对于那些来这里寻找一个稳定的插件来轻松调整网页背景图像大小的人来说,有一个很好的 Jquery 插件可以做到这一点!

参见: jQuery 轻松背景调整大小


相关OP 问题:

  • 对旧版浏览器的支持:

IE6 的市场份额目前非常低。 Safari、Firefox 和 Opera 等其他浏览器也是如此。

在此处输入图像描述

查看更多 详细信息在这里!


  • 将代码包装到 Jquery 插件中:

获取您的代码并从中构建一个插件可以通过四个基本步骤完成步骤:

  1. 跨库安全
  2. 创建并命名您的插件函数
  3. 允许可链接性
  4. 开始构建插件功能

(1)
首先要做的是创建一个包装函数,它允许您使用 $ 并且不会与可能包含的其他 JavaScript 框架发生冲突:

(function($) {
  // safe to use $ here and not cause conflicts
})(jQuery);

(2)
接下来,创建您的插件将驻留在其中的函数。无论您如何命名此函数,您和其他人都将如何使用您的插件:

(function($) {
  $.fn.mypluginname = function() {
    // the plugin functionality goes in here
  }
})(jQuery);

(3)
此时,请记住,由于 jQuery 采用任何选择器,因此您可能正在处理一个或多个对象。这意味着您需要确保您的插件循环遍历选择器匹配的每个元素并应用插件功能:

(function($) {
  $.fn.mypluginname = function() {
    return this.each(function() {
      // apply plugin functionality to each element
    });
  }
})(jQuery);

(4)
在此阶段,您开始构建插件功能!对于您的情况,调整背景大小的所有必要步骤。

最终结果将是这样的:

$('div').mypluginname();

这是一个很好的教程,可以引导您完成整个过程,甚至可以添加您提到的配置选项!

请参阅:从头开始创建 jQuery 插件

For those who came here looking for a stable plugin to easily resize the background image of a web page, there is a good Jquery Plugin that does just that!

See: jQuery Easy Background Resize


Related to the OP questions:

  • Support for older browsers:

The market share for IE6 is today very low. The same goes to other browsers like Safari, Firefox, and Opera.

enter image description here

See more details here!


  • Wrap the code into a Jquery Plug-In:

Take your code and build a plug-in out of it can be done in four basic steps:

  1. Cross Library Safety
  2. Create and Name Your Plugin Function
  3. Allow chainability
  4. Start Building Plugin Functionality

(1)
The first thing to do is create a wrapper function which allows you to use $ and not cause conflicts with other JavaScript frameworks that may be included:

(function($) {
  // safe to use $ here and not cause conflicts
})(jQuery);

(2)
Next, create the function inside which your plugin will reside. Whatever you name this function will be how you and others use your plugin:

(function($) {
  $.fn.mypluginname = function() {
    // the plugin functionality goes in here
  }
})(jQuery);

(3)
At this point, keep in mind that because jQuery takes any selector, you could be dealing with one or more objects. This means you need to be sure that your plug-in loops through each element matched by the selector and applies the plug-in functionality:

(function($) {
  $.fn.mypluginname = function() {
    return this.each(function() {
      // apply plugin functionality to each element
    });
  }
})(jQuery);

(4)
At this stage, you start building your plugin functionality! In your case, all the necessary steps for the background resize.

The end Result will be something along this line:

$('div').mypluginname();

Here's a good tutorial to walk you through the entire process, even adding configuration options as you mentioned!

See: Creating A jQuery Plugin From Scratch

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文