Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

311
Views
¿Cómo obtengo el tamaño de la imagen de fondo en jQuery?

El problema es sencillo. ¿Cómo obtengo el tamaño de la imagen de fondo de un div (ancho y alto) en jQuery? ¿Es posible? Pensé que esto funcionaría:

 jQuery('#myDiv').css('background-image').height();

El mensaje de error que recibo es que esto no es una función.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Una versión más. No se necesita manipulación DOM, se admiten todos los caracteres en el nombre del archivo de imagen.

ACTUALIZAR Vea una versión alternativa a continuación.

 var image_url = $('#something').css('background-image'), image; // Remove url() or in case of Chrome url("") image_url = image_url.match(/^url\("?(.+?)"?\)$/); if (image_url[1]) { image_url = image_url[1]; image = new Image(); // just in case it is not already loaded $(image).load(function () { alert(image.width + 'x' + image.height); }); image.src = image_url; }

solución 2018

Esta respuesta todavía recibe votos a favor 5 años después. Pensé que compartiré una solución más completa. Esto se basa en el código original y lo envuelve en una función. Utiliza jQuery Deferred Object, agrega manejo de errores y actualiza RegExp para que coincida con 3 casos posibles: url() , url("") y url('') . También funciona en jQuery 1 a 3.

 var getBackgroundImageSize = function(el) { var imageUrl = $(el).css('background-image').match(/^url\(["']?(.+?)["']?\)$/); var dfd = new $.Deferred(); if (imageUrl) { var image = new Image(); image.onload = dfd.resolve; image.onerror = dfd.reject; image.src = imageUrl[1]; } else { dfd.reject(); } return dfd.then(function() { return { width: this.width, height: this.height }; }); }; // // Usage // getBackgroundImageSize(jQuery('#mydiv')) .then(function(size) { console.log('Image size is', size.width, size.height); }) .fail(function() { console.log('Could not get size because could not load image'); });
over 4 years ago · Santiago Trujillo Report

0

Tendrás que hacer algo como esto:

 var url = $('#myDiv').css('background-image').replace('url(', '').replace(')', '').replace("'", '').replace('"', ''); var bgImg = $('<img />'); bgImg.hide(); bgImg.bind('load', function() { var height = $(this).height(); alert(height); }); $('#myDiv').append(bgImg); bgImg.attr('src', url);

Debido a la simplicidad del código, no puede usar paréntesis ni comillas en las URL de sus imágenes de fondo. Sin embargo, el código podría extenderse para un mayor soporte. Solo quería transmitir la idea general.

over 4 years ago · Santiago Trujillo Report

0

Respuesta tardía, pero también podrías hacer esto:

 var img = new Image; img.src = $('#myDiv').css('background-image').replace(/url\(|\)$/ig, ""); var bgImgWidth = img.width; var bgImgHeight = img.height;

Entonces no tienes que manipular los objetos dom;

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!