我正在使用 JQuery 插件制作全屏图像。我正在使用一些 css 使图像适合屏幕,但是当我单击退出全屏然后单击返回全屏时,它似乎忽略了我设置的 css。这部分代码是我接手元素时继承的代码,所以有些代码我不完全理解。
.fullBg {
position: absolute;
top: 0px;
left: 0px;
overflow: auto;
z-index: 1;
width:100%;
height:100%;
}
这是JQuery代码;
( function($) {
$.fn.fullBG = function(){
var el = $(this);
el.addClass( 'fullBg' );
function resizeImg() {
var imgwidth = el.width(),
imgheight = el.height(),
winwidth = $(window).width(),
winheight = $(window).height(),
heightdiff = winwidth / imgwidth * imgheight,
new_width = ( heightdiff > winheight ) ? winwidth : winheight / imgheight * imgwidth,
new_height = ( heightdiff > winheight ) ? winwidth / imgwidth * imgheight : winheight;
el.css( { 'width' : new_width + 'px', 'height' : new_height + 'px', 'visibility' : 'visible' } );
}
$(window).resize( function() {
resizeImg();
} ).resize();
};
} )(jQuery)
当我点击全屏时,它会将我送回原始图像,这段代码似乎可以处理这个问题。我注意到有一段删除类“fullbackground”的代码,这会导致我的问题吗?
<img id='fullbackground' height="480px" width="640px" alt="" onclick="ExitfullBackgroundImage()" />
<script type="text/javascript">
var IsFull = false;
var IsShowed = false;
var isShowedAbout = false;
function ShowIcon() {
if (!IsFull) {
var p = $("#fullbackground");
var position = p.position();
$("#divIcon").css("left", (position.left + 600) + "px");
$("#divIcon").css("top", (position.top + 440) + "px");
$("#divIcon").show();
}
else {
$("#divIcon").hide();
}
}
function HideIcon() {
$("#divIcon").hide();
}
function fullBackgroundImage() {
IsFull = true;
$("#fullbackground").fullBg();
}
function ExitfullBackgroundImage() {
if (IsFull) {
$("#fullbackground").width(640);
$("#fullbackground").height(480);
$("#fullbackground").removeClass("fullBg");
IsFull = false;
}
else if (!IsFull) {
IsFull = true;
$("#fullbackground").fullBg();
}
最佳答案
CSS 中的样式附加到 fullBg
类,单击图像时会删除该类名。您可以做的是在 else 语句中添加类,这样当再次单击图像时,类名就会被设置:
function ExitfullBackgroundImage() {
if (IsFull) {
$("#fullbackground").width(640);
$("#fullbackground").height(480);
$("#fullbackground").removeClass("fullBg");
IsFull = false;
}
else if (!IsFull) {
IsFull = true;
$("#fullbackground").attr("style",""); // <-- clear the inline styles set by javascript
$("#fullbackground").addClass("fullBg"); // <-- add class
$("#fullbackground").fullBg();
}
}
但是,我会考虑通过更多地使用 css 来改进此代码:
CSS:
#fullbackground {
width: 640px;
height: 480px;
}
#fullbackground.fullBg {
position: absolute;
top: 0px;
left: 0px;
overflow: auto;
z-index: 1;
width:100%;
height:100%;
}
Javascript:
function ExitfullBackgroundImage() {
$("#fullbackground").toggleClass("fullBg");
// toggleclass 'toggles' the classname on/off
if($("#fullbackground").hasClass("fullBg")){
$("#fullbackground").fullBg();
} else {
$("#fullbackground").attr("style","");
}
}
关于javascript - JQuery 全背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20347872/