Могу ли я исчезать в фоновом изображении (CSS: background-image) с помощью jQuery? - программирование
Подтвердить что ты не робот

Могу ли я исчезать в фоновом изображении (CSS: background-image) с помощью jQuery?

У меня есть элемент div с текстом в нем и фоновым изображением, которое устанавливается через свойство CSS background-image. Можно ли затухать в фоновом изображении через jQuery?

HTML:

<div>Text</div>

CSS

div {
   background-repeat: no-repeat;
   background-position: center;
   background-size: contain;
   background-image: url(http://upload.wikimedia.org/wikipedia/commons/8/84/Konqi_svg.svg);
   border: 1px solid #666;
   height: 10em;
}

ИЗМЕНИТЬ

Я сделал fiddle, иллюстрирующий мой сценарий. В основном это настраивает начальные background-image и a transition и меняет background-image на jQuery. В моем тестировании нет анимированного перехода между двумя изображениями.

EDIT2

Мой измененный fiddle работает!

4b9b3361

Ответ 2

Я искал веки, и, наконец, я собрал все вместе, чтобы найти свое решение. Говорят, вы не можете затухать/вне фонового изображения с html-фона. Это определенно неправильно, поскольку вы можете понять, выполнив приведенную ниже демонстрационную версию

CSS

html, body

height: 100%;   /* ges Hoehe der Seite -> weitere Hoehenangaben werden relativ hierzu ausgewertet */
overflow: hidden;   /*  hide scrollbars */
opacity: 1.0;
-webkit-transition: background 1.5s linear;
-moz-transition: background 1.5s linear;
-o-transition: background 1.5s linear;
-ms-transition: background 1.5s linear;
transition: background 1.5s linear;

Изменение фонового изображения тела теперь легко можно выполнить с помощью JavaScript:

switch (dummy)

case 1:

$(document.body).css({"background-image": "url("+URL_of_pic_One+")"});
waitAWhile();

case 2:
$(document.body).css({"background-image": "url("+URL_of_pic_Two+")"});
waitAWhile();

Ответ 3

Вы можете указать значение непрозрачности как

div {opacity: 0.4;}

Для IE вы можете указать

div { filter:alpha(opacity=10));}

Опустите значение - Увеличьте прозрачность.

Ответ 4

Невозможно сделать это именно так, но вы можете наложить непрозрачный div между div с фоновым изображением и текстом и вытереть из него, следовательно, придать виду, что фон затухает.

Ответ 5

Это то, что сработало для моего, и его чистого css


CSS

html {
    padding: 0;
    margin: 0;
    width: 100%;
    height: 100%;
  }

  body {
    padding: 0;
    margin: 0;
    width: 100%;
    height: 100%;
  }

  #bg {
    width: 100%;
    height: 100%;
    background: url('/image.jpg/') no-repeat center center fixed;

    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;

    -webkit-animation: myfirst 5s ; /* Chrome, Safari, Opera */
    animation: myfirst 5s ;
  }

  /* Chrome, Safari, Opera */
  @-webkit-keyframes myfirst {
    from {opacity: 0.2;}
    to {opacity: 1;}
  }

  /* Standard syntax */
  @keyframes myfirst {
    from {opacity: 0.2;}
    to {opacity: 1;}
  }

HTML

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
  <div id="bg">
    <!-- content here -->
  </div> <!-- end bg -->
</body>
</html>

Ответ 6

В современном браузере я предпочитаю очень легкий подход с немного Js и CSS3...

transition: background 300ms ease-in 200ms;

Посмотрите на эту демонстрацию:

http://codepen.io/nicolasbonnici/pen/gPVNbr

Ответ 7

Вы можете пометить фоновое изображение различными способами, поскольку Firefox 4...

Ваш CSS:

.box {
    background: #CCCCCC;
    -webkit-transition: background 0.5s linear;
    -moz-transition: background 0.5s linear;
    -o-transition: background 0.5s linear;
    transition: background 0.5s linear;
    }
.box:hover {
    background: url(path/to/file.png) no-repeat #CCCCCC;
    }

Ваш XHTML:

<div class="box">
    Some Text …
</div>

И вот оно.

Ответ 8

JQuery

 $("div").fadeTo(1000 , 1);

CSS

    div {
     background: url("../images/example.jpg") no-repeat center; 
    opacity:0;
    Height:100%;
    }

HTML

<div></div>

Ответ 9

Я знаю, что опаздываю, но я нашел способ использования jquery, который работает в каждом браузере (я тестировал его на chrome, firefox и Ie 9), а элементы fore-ground всегда отображаются вместо свойства перехода css3.

создать 2 абсолютную оболочку и использовать z-index.

Сначала установите элементы, которые должны быть на переднем плане с наивысшим значением свойства z-index, и другими элементами (все они включены в тело, так: body {}) с более низким значением свойства z-index чем передние наземные элементы, по крайней мере, на 2 числа ниже.

Часть HTML:

         <div class="wrapper" id="wrapper1"></div>
         <div class="wrapper" id="wrapper2"></div>

css part:

        .fore-groundElements{              //select all fore-ground elements
                  z-index:0;               //>=0
        }
       .wrapper{
                  background-size: cover;
                  width:100%;
                  height:100%;
                  background-size: 100% 100%;
                  position:absolute;
         }

        #wrapper1{
               z-index:-1; 
        }


        #wrapper2{
                 z-index:-2;
         }
         body{

              height:100%;
              width:100%;
              margin:0px;   
              display:cover;
              z-index:-3                          //<=-3
         }

чем javascript/jquery one:

Мне нужно было изменить фоновое изображение каждые три секунды, поэтому я использовал тайм-аут набора.

это код:

  $(document).ready(main);

  var main = function(){

             var imgPath=[imagesPath1,..,...];                 // the array in which store the image paths

             var newWrapper;                     // the wrapper to display 
             var currentWrapper;                 //the current displayed wrapper which has to be faded
             var l=2;                             // the next image index  to be displayed, it is set to 2 because the first two position of the array(first two images) start already setted up
             var imgNumber= imgPath.length;        //to know when the images are over and restart the carousel
             var currentImg;                       //the next image path to be displayed


             $('#wrapper1').css("background-image", 'url'+imgPath[0]);         //pre set the first wrapper background images
             $('#wrapper2').css("background-image", 'url'+imgPath[1]);          //pre set the first wrapper background images   

             setInterval(myfunction,3000);                //refresh the background image every three seconds

             function myfunction(){
                    if(l===imgNumber-1){               //restart the carousel if every single image has already been displayed                  
                         l=0;
                     };

             if(l%2==0||l%2==2){                    //set the wrapper that will be displaied after the fadeOut callback function
                  currentWrapper='#wrapper1';         
                  newWrapper='#wrapper2';
             }else{
                  currentWrapper='#wrapper2';
                  newWrapper='#wrapper1';
             };
             currentImg=imgPath[l];
            $(currentWrapper).fadeOut(1000,function(){               //fade out the current wrapper, so now the back-ground wrapper is fully displayed
                  $(newWrapper).css("z-index", "-1");                //move the shown wrapper in the fore-ground
                  $(currentWrapper).css("z-index","-2");             //move the hidden wrapper in the back ground
                  $(currentWrapper).css("background-image",'url'+currentImg);                   // sets up the next image that is now shown in the actually hidden background wrapper
                  $(currentWrapper).show();          //shows the background wrapper, which is not visible yet, and it will be shown the next time the setInterval event will be triggered
                  l++;                         //set the next image index that will be set the next time the setInterval event will be triggered 
             });


         };                   //end of myFunction
  }                          //end of main

Надеюсь, что мой ответ ясен, если вам нужно больше пояснить комментарий.

извините за мой английский:)