Ir para conteúdo
Hamilcar

[Resolvido] Jquery não carrega

Recommended Posts

Bom dia galera!

Estou com um problema aqui que não sei o que acontece, nas minhas páginas uso o jquery,  acredito que ele esteja dando problemas, pois tenho um quadro de slides e este quando chamo jquery direto da pasta, o slide não funciona, e quando coloco pra chamar via url, o slide funciona. Outra coisa, na parte de ajax, não consigo fazer as requisições, não funciona, não funciona localmente e não funciona em duas hospedagens gratuita que uso pra teste, mas funciona tudo na minha hospedagem paga, o mesmo código, sem tirar nem por nada, precisava funcionar pelo menos localmente para poder fazer manutenções localhost, alguém já passou por isto?

Compartilhar este post


Link para o post
Compartilhar em outros sites

Tente usar o seguinte script 

 

backstretch.js

/*
 * Backstretch
 * http://srobbin.com/jquery-plugins/backstretch/
 *
 * Copyright (c) 2013 Scott Robbin
 * Licensed under the MIT license.
 */

;(function ($, window, undefined) {
  'use strict';

  /* PLUGIN DEFINITION
   * ========================= */

  $.fn.backstretch = function (images, options) {
    // We need at least one image or method name
    if (images === undefined || images.length === 0) {
      $.error("No images were supplied for Backstretch");
    }

    /*
     * Scroll the page one pixel to get the right window height on iOS
     * Pretty harmless for everyone else
    */
    if ($(window).scrollTop() === 0 ) {
      window.scrollTo(0, 0);
    }

    return this.each(function () {
      var $this = $(this)
        , obj = $this.data('backstretch');

      // Do we already have an instance attached to this element?
      if (obj) {

        // Is this a method they're trying to execute?
        if (typeof images == 'string' && typeof obj[images] == 'function') {
          // Call the method
          obj[images](options);

          // No need to do anything further
          return;
        }

        // Merge the old options with the new
        options = $.extend(obj.options, options);

        // Remove the old instance
        obj.destroy(true);
      }

      obj = new Backstretch(this, images, options);
      $this.data('backstretch', obj);
    });
  };

  // If no element is supplied, we'll attach to body
  $.backstretch = function (images, options) {
    // Return the instance
    return $('body')
            .backstretch(images, options)
            .data('backstretch');
  };

  // Custom selector
  $.expr[':'].backstretch = function(elem) {
    return $(elem).data('backstretch') !== undefined;
  };

  /* DEFAULTS
   * ========================= */

  $.fn.backstretch.defaults = {
      centeredX: true   // Should we center the image on the X axis?
    , centeredY: true   // Should we center the image on the Y axis?
    , duration: 5000    // Amount of time in between slides (if slideshow)
    , fade: 0           // Speed of fade transition between slides
  };

  /* STYLES
   * 
   * Baked-in styles that we'll apply to our elements.
   * In an effort to keep the plugin simple, these are not exposed as options.
   * That said, anyone can override these in their own stylesheet.
   * ========================= */
  var styles = {
      wrap: {
          left: 0
        , top: 0
        , overflow: 'hidden'
        , margin: 0
        , padding: 0
        , height: '100%'
        , width: '100%'
        , zIndex: -999999
      }
    , img: {
          position: 'absolute'
        , display: 'none'
        , margin: 0
        , padding: 0
        , border: 'none'
        , width: 'auto'
        , height: 'auto'
        , maxHeight: 'none'
        , maxWidth: 'none'
        , zIndex: -999999
      }
  };

  /* CLASS DEFINITION
   * ========================= */
  var Backstretch = function (container, images, options) {
    this.options = $.extend({}, $.fn.backstretch.defaults, options || {});

    /* In its simplest form, we allow Backstretch to be called on an image path.
     * e.g. $.backstretch('/path/to/image.jpg')
     * So, we need to turn this back into an array.
     */
    this.images = $.isArray(images) ? images : [images];

    // Preload images
    $.each(this.images, function () {
      $('<img />')[0].src = this;
    });    

    // Convenience reference to know if the container is body.
    this.isBody = container === document.body;

    /* We're keeping track of a few different elements
     *
     * Container: the element that Backstretch was called on.
     * Wrap: a DIV that we place the image into, so we can hide the overflow.
     * Root: Convenience reference to help calculate the correct height.
     */
    this.$container = $(container);
    this.$root = this.isBody ? supportsFixedPosition ? $(window) : $(document) : this.$container;

    // Don't create a new wrap if one already exists (from a previous instance of Backstretch)
    var $existing = this.$container.children(".backstretch").first();
    this.$wrap = $existing.length ? $existing : $('<div class="backstretch"></div>').css(styles.wrap).appendTo(this.$container);

    // Non-body elements need some style adjustments
    if (!this.isBody) {
      // If the container is statically positioned, we need to make it relative,
      // and if no zIndex is defined, we should set it to zero.
      var position = this.$container.css('position')
        , zIndex = this.$container.css('zIndex');

      this.$container.css({
          position: position === 'static' ? 'relative' : position
        , zIndex: zIndex === 'auto' ? 0 : zIndex
        , background: 'none'
      });
      
      // Needs a higher z-index
      this.$wrap.css({zIndex: -999998});
    }

    // Fixed or absolute positioning?
    this.$wrap.css({
      position: this.isBody && supportsFixedPosition ? 'fixed' : 'absolute'
    });

    // Set the first image
    this.index = 0;
    this.show(this.index);

    // Listen for resize
    $(window).on('resize.backstretch', $.proxy(this.resize, this))
             .on('orientationchange.backstretch', $.proxy(function () {
                // Need to do this in order to get the right window height
                if (this.isBody && window.pageYOffset === 0) {
                  window.scrollTo(0, 1);
                  this.resize();
                }
             }, this));
  };

  /* PUBLIC METHODS
   * ========================= */
  Backstretch.prototype = {
      resize: function () {
        try {
          var bgCSS = {left: 0, top: 0}
            , rootWidth = this.isBody ? this.$root.width() : this.$root.innerWidth()
            , bgWidth = rootWidth
            , rootHeight = this.isBody ? ( window.innerHeight ? window.innerHeight : this.$root.height() ) : this.$root.innerHeight()
            , bgHeight = bgWidth / this.$img.data('ratio')
            , bgOffset;

            // Make adjustments based on image ratio
            if (bgHeight >= rootHeight) {
                bgOffset = (bgHeight - rootHeight) / 2;
                if(this.options.centeredY) {
                  bgCSS.top = '-' + bgOffset + 'px';
                }
            } else {
                bgHeight = rootHeight;
                bgWidth = bgHeight * this.$img.data('ratio');
                bgOffset = (bgWidth - rootWidth) / 2;
                if(this.options.centeredX) {
                  bgCSS.left = '-' + bgOffset + 'px';
                }
            }

            this.$wrap.css({width: rootWidth, height: rootHeight})
                      .find('img:not(.deleteable)').css({width: bgWidth, height: bgHeight}).css(bgCSS);
        } catch(err) {
            // IE7 seems to trigger resize before the image is loaded.
            // This try/catch block is a hack to let it fail gracefully.
        }

        return this;
      }

      // Show the slide at a certain position
    , show: function (newIndex) {

        // Validate index
        if (Math.abs(newIndex) > this.images.length - 1) {
          return;
        }

        // Vars
        var self = this
          , oldImage = self.$wrap.find('img').addClass('deleteable')
          , evtOptions = { relatedTarget: self.$container[0] };

        // Trigger the "before" event
        self.$container.trigger($.Event('backstretch.before', evtOptions), [self, newIndex]); 

        // Set the new index
        this.index = newIndex;

        // Pause the slideshow
        clearInterval(self.interval);

        // New image
        self.$img = $('<img />')
                      .css(styles.img)
                      .bind('load', function (e) {
                        var imgWidth = this.width || $(e.target).width()
                          , imgHeight = this.height || $(e.target).height();
                        
                        // Save the ratio
                        $(this).data('ratio', imgWidth / imgHeight);

                        // Show the image, then delete the old one
                        // "speed" option has been deprecated, but we want backwards compatibilty
                        $(this).fadeIn(self.options.speed || self.options.fade, function () {
                          oldImage.remove();

                          // Resume the slideshow
                          if (!self.paused) {
                            self.cycle();
                          }

                          // Trigger the "after" and "show" events
                          // "show" is being deprecated
                          $(['after', 'show']).each(function () {
                            self.$container.trigger($.Event('backstretch.' + this, evtOptions), [self, newIndex]);
                          });
                        });

                        // Resize
                        self.resize();
                      })
                      .appendTo(self.$wrap);

        // Hack for IE img onload event
        self.$img.attr('src', self.images[newIndex]);
        return self;
      }

    , next: function () {
        // Next slide
        return this.show(this.index < this.images.length - 1 ? this.index + 1 : 0);
      }

    , prev: function () {
        // Previous slide
        return this.show(this.index === 0 ? this.images.length - 1 : this.index - 1);
      }

    , pause: function () {
        // Pause the slideshow
        this.paused = true;
        return this;
      }

    , resume: function () {
        // Resume the slideshow
        this.paused = false;
        this.next();
        return this;
      }

    , cycle: function () {
        // Start/resume the slideshow
        if(this.images.length > 1) {
          // Clear the interval, just in case
          clearInterval(this.interval);

          this.interval = setInterval($.proxy(function () {
            // Check for paused slideshow
            if (!this.paused) {
              this.next();
            }
          }, this), this.options.duration);
        }
        return this;
      }

    , destroy: function (preserveBackground) {
        // Stop the resize events
        $(window).off('resize.backstretch orientationchange.backstretch');

        // Clear the interval
        clearInterval(this.interval);

        // Remove Backstretch
        if(!preserveBackground) {
          this.$wrap.remove();          
        }
        this.$container.removeData('backstretch');
      }
  };

  /* SUPPORTS FIXED POSITION?
   *
   * Based on code from jQuery Mobile 1.1.0
   * http://jquerymobile.com/
   *
   * In a nutshell, we need to figure out if fixed positioning is supported.
   * Unfortunately, this is very difficult to do on iOS, and usually involves
   * injecting content, scrolling the page, etc.. It's ugly.
   * jQuery Mobile uses this workaround. It's not ideal, but works.
   *
   * Modified to detect IE6
   * ========================= */

  var supportsFixedPosition = (function () {
    var ua = navigator.userAgent
      , platform = navigator.platform
        // Rendering engine is Webkit, and capture major version
      , wkmatch = ua.match( /AppleWebKit\/([0-9]+)/ )
      , wkversion = !!wkmatch && wkmatch[ 1 ]
      , ffmatch = ua.match( /Fennec\/([0-9]+)/ )
      , ffversion = !!ffmatch && ffmatch[ 1 ]
      , operammobilematch = ua.match( /Opera Mobi\/([0-9]+)/ )
      , omversion = !!operammobilematch && operammobilematch[ 1 ]
      , iematch = ua.match( /MSIE ([0-9]+)/ )
      , ieversion = !!iematch && iematch[ 1 ];

    return !(
      // iOS 4.3 and older : Platform is iPhone/Pad/Touch and Webkit version is less than 534 (ios5)
      ((platform.indexOf( "iPhone" ) > -1 || platform.indexOf( "iPad" ) > -1  || platform.indexOf( "iPod" ) > -1 ) && wkversion && wkversion < 534) ||
      
      // Opera Mini
      (window.operamini && ({}).toString.call( window.operamini ) === "[object OperaMini]") ||
      (operammobilematch && omversion < 7458) ||
      
      //Android lte 2.1: Platform is Android and Webkit version is less than 533 (Android 2.2)
      (ua.indexOf( "Android" ) > -1 && wkversion && wkversion < 533) ||
      
      // Firefox Mobile before 6.0 -
      (ffversion && ffversion < 6) ||
      
      // WebOS less than 3
      ("palmGetResource" in window && wkversion && wkversion < 534) ||
      
      // MeeGo
      (ua.indexOf( "MeeGo" ) > -1 && ua.indexOf( "NokiaBrowser/8.5.0" ) > -1) ||
      
      // IE6
      (ieversion && ieversion <= 6)
    );
  }());

}(jQuery, window));

Slide js

 

    <script type="text/javascript">

    /* backstretch slider */
    $('.header-slide').backstretch([
            "http://localhost/IMOB/assets/imagens/slides/cfb34816a5e2275cc9afba4fee485862.jpg",
      
            "http://localhost/IMOB/assets/imagens/slides/d34bbf02011cd7e3e7dab9bce8ffb90c.jpg",
      
            ], {
        fade: 850,
        duration: 4000
    });
      
</script> 

onde for teu slide 

chama o slide

 

 <div class="header-slide">
   
</div>

Veja se vai funcionar

Compartilhar este post


Link para o post
Compartilhar em outros sites
Em 22/03/2020 at 20:56, Jack Oliveira disse:

Poste teu código 

O código do jquery e bootstrap ao abrí-los com a IDE, aparece uma mensagem de que o código não é utf-8 e abrindo assim mesmo, bagunça parte do código, parece ter danificado por causa da codificação, então, abri o código no netbeans e o abri o online no browser, então copiei e colei direto no do netbeans, aí os erros sumiram do console e está funcionando, o engraçado é que na hospedagem funciona, mas deu certo. agora meu localhost tá funcionando de novo, mas, se fizer download do código do site, o código do bootstrap e jquery bagunça de novo, acho que o cliente ftp faz isso, estou usando o filezilla. obrigado a todos!

Compartilhar este post


Link para o post
Compartilhar em outros sites

Crie uma conta ou entre para comentar

Você precisar ser um membro para fazer um comentário

Criar uma conta

Crie uma nova conta em nossa comunidade. É fácil!

Crie uma nova conta

Entrar

Já tem uma conta? Faça o login.

Entrar Agora

  • Conteúdo Similar

    • Por Thiago Duarte
      Oi, gostaria de arrastar imagem e ao soltar formar bloco html, meu bloco de html ficaria com nome, content-1.html, content-2.html, etc
       
      Alguem pode me ajudar?
    • Por ILR master
      Salve galera.
       
      Vou publicar um evento e quero colocar um Cronômetro regressivo que mostre em tempo real os dias, horas e minutos que faltam para determinada data, tipo:.
      Faltam 5 dias, 12:30:00 para inauguração.
       
      Qdo chegar no dia, quero que apenas apareça uma mensagem.
       
      Alguém pode me ajudar?
    • Por gersonab
      bom dia
      tenho uma aplicação onde gero um arquivo em pdf, gostaria de recuperar a url do pdf q foi criado, pois quando este é criado ele abre automaticamente e ou ja faz o download do mesmo, preciso da url para enviar para outros.
      <button type="button" class="btn btn-outline-primary" onclick="createPDF();">Imprimir</button> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.4.1/jspdf.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/canvas2image@1.0.5/canvas2image.min.js"></script> <script language="javascript"> (function($){ $.fn.createPdf = function(parametros) { var config = { 'fileName':'html-to-pdf' }; if (parametros){ $.extend(config, parametros); } var orig = $(this); var widthOrig = $(orig).width(); $(orig).width(900); var quotes = document.getElementById($(orig).attr('id')); html2canvas(quotes, { onrendered: function(canvas) { var pdf = new jsPDF('p', 'pt', 'letter'); for (var i = 0; i <= quotes.clientHeight/900; i++) { var srcImg = canvas; var sX = 0; var sY = 900*i; var sWidth = 900; var sHeight = 900; var dX = 0; var dY = 0; var dWidth = 900; var dHeight = 900; window.onePageCanvas = document.createElement("canvas"); onePageCanvas.setAttribute('width', 900); onePageCanvas.setAttribute('height', 900); var ctx = onePageCanvas.getContext('2d'); ctx.drawImage(srcImg,sX,sY,sWidth,sHeight,dX,dY,dWidth,dHeight); var canvasDataURL = onePageCanvas.toDataURL("image/png", 1.0); var width = onePageCanvas.width; var height = onePageCanvas.clientHeight; if (i > 0) { pdf.addPage(612, 791); } pdf.setPage(i+1); pdf.addImage(canvasDataURL, 'PNG', 20, 40, (width*.62), (height*.62)); // Retirar o comentário caso queira ver como está sendo gerado o canvas. //document.body.appendChild(onePageCanvas); } pdf.save(config.fileName); $(orig).width(widthOrig); } }); }; })(jQuery); function createPDF() { $('#renderPDF').createPdf({ 'fileName' : '<?php echo $usercli['idocl']; ?>' }); }  
    • Por gersonab
      Boa tarde a todos.
      tenho pesquisado e ainda não encontrei uma forma de montar uma imagem online, tipo, tenho uma área de 400px por 400px , nesta gostaria de acrescentar algumas imagens que já tenho, tipo clicar e arrastar para dentro, sendo que estas imagens já se encontram online no site, seria mais ou menos assim : poderia colocar dentro desta área uma imagem do gato , do cachorro e ou outra. Não sei qual biblioteca ou forma de fazer.
      gostaria da ajuda para iniciar, desde já agradeço.
    • Por Danilo - Jesus voltará!
      Olá pessoal, tenho uma div a qual através de um select categorias eu trago dados de empresas do banco, aí preciso clicar nas listagens das empresas e pegar o ID quando clica no checkbox e gravar pelo ajax novamente na session feita no arquivo php tipo um carrinho de compras, que essa parte já tenho... só não to conseguindo pegar os ids gerados dinamicamente no retorno feito do ajax, eles aparecem com F12 ao inspecionar, mas não aceita eu clicar para pegar o ID, acho que é algo de DOM, mas não to sabendo fazer... alguém aí saberia me ajudar como pegar esses ids ao clicar, já que eles vem dinamicamente?
       
      obrigado
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.