Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/373.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
什么';将SASS变量传递给javascript的行业标准方法是什么?_Javascript_Html_Sass - Fatal编程技术网

什么';将SASS变量传递给javascript的行业标准方法是什么?

什么';将SASS变量传递给javascript的行业标准方法是什么?,javascript,html,sass,Javascript,Html,Sass,我环顾四周,看到了一个解决方案,在html中,有一个专门用于将sass变量传递给javascript的标记。我说的是第二个答案 我也尝试过使用html <div class="selector"></div> 但是看看开发工具中的dom,即使我们可以在呈现的页面上看到它,它也没有被添加,所以我不能用javascript来获取它 $('.selector').text() 每个人都是如何做到的?不确定“行业标准”,但这是一种非常方便的技术,也不太难。伪元素的内容不能通

我环顾四周,看到了一个解决方案,在html中,有一个专门用于将sass变量传递给javascript的标记。我说的是第二个答案

我也尝试过使用html

<div class="selector"></div>
但是看看开发工具中的dom,即使我们可以在呈现的页面上看到它,它也没有被添加,所以我不能用javascript来获取它

$('.selector').text()
每个人都是如何做到的?

不确定“行业标准”,但这是一种非常方便的技术,也不太难。伪元素的内容不能通过
text()
获得,但必须使用
getComputedStyle

使用
body:after
的示例:

Sass(使用):

JavaScript

if (window.getComputedStyle) {
  var mq = window.getComputedStyle(document.body,':after').getPropertyValue('content');
}

if (mq.indexOf('small') !== -1) {
  // do something
}

信用证:我第一次在这里看到这种技术:

我认为通过CSS
内容
属性注入SASS变量是一种非常黑客的方法

相反,您可以将变量存储在单独的位置,并让SASS和JS读取它们

首先,将断点列表存储在
breakpoints.json
文件中:

然后使用Ruby读取此JSON文件,并通过SASS函数将其内容作为SASS列表提供。将其放入指南针
config.rb

在SASS代码中,读取如下断点:

$breakpoints: breakpoints()
在JS中,使用jQuery的
.get
方法请求JSON文件,如下所示:

当我组装这个设置时,我发现了一个现有的解决方案,但我决定使用我最喜欢的SASS工具重新实现它:和

为了您的方便,我构建了一个概念验证,所有内容都设置得很好,其中包含一些丑陋的JS代码。:)


这里有一个

通过CSS
content
属性共享状态似乎脏了。我也不喜欢提出额外的XHR请求

我曾想过构建一个定制的解决方案,只需编译SASS文件和JS模块。但事实证明有一个名为npm的
npm
包。正是这样。输出格式非常灵活,我很快就将其设置为
Grunt.js
任务

$npm安装rosetta

下面是Gruntfile.js示例:

和package.json:


毕竟,您只需要在SASS中导入_shared_variables.scs,并在JavaScript中使用rosetta.js模块来访问公共变量。当您更改*.rose文件时,您的样式和JS将被更新。

如果您使用的是
GULP
GRUNT
(我希望您使用的是第一个)

此示例显示了如何使用
gulp
: 在gulpfile或其他文件中定义颜色,然后将其导入gulpfile,然后可以动态构建
SCSS
变量和javascript,如下所示:

变量_template.scss(不导入主scss文件) app.js(包含colors变量的一些js文件) gulpfile.js
SCSS变量的类似NPM gulp包:


您无法将变量从SASS传递到JS,您给出的答案只是将其转换为JQuery。总之,JS是一个行业标准,您可以将其与CSS结合使用;)也许SASS并不意味着要传递给JavaScript,但我可以想到至少有一个地方它是有意义的。假设我正在为桌面和移动设备制作一个响应性布局。我在SASS中将断点设置为768px的宽度。在JS中,最好知道断点是什么,而不是声明一个新变量来分别维护这两个变量。@Jack“的意思是”?web开发的历史是解决现实世界问题的聪明黑客之一。你认为这些最初是如何制作的?@steveax聪明的黑客听起来不像是行业标准。就我个人而言,我会看到自己用PHP定义变量,并将它们分别传递给SASS和JS。这在性能方面相当糟糕,因为浏览器将不得不请求额外的JSON文件,而等待这一点将阻碍其他依赖于这些变量的js。你是对的。但是,如果您将请求者放在一个单独的小JS文件中并尽早包含它,那么JSON文件将与CSS同时下载,JS断点将在应用CSS媒体查询后不久应用。“然后使用Ruby”。就像我一开始就用Ruby一样。这与问题完全无关,不应该包括在内,因为这可能只适用于使用Ruby的开发人员的一小部分。@vsync这个答案是3.5年前写的。当时,唯一可用的(功能齐全的)Sass实现是用Ruby编写的。目前,最流行的Sass实现是用C编写的
libsass
,通常用作npm包(包装到JS中)。C的运行速度更快,但开发速度要慢得多,所以下一个官方实现将用Dart编写。几年后,另一个脚本kiddie会告诉你:“Wat?npm安装?你太不相关了,老头子!”
getComputedStyle
会导致样式重新调整/并强制布局,这对性能非常不利,如果可能的话,最好避免它。@RayShan-如果你在页面呈现之前使用它,仍然很好,如果重新油漆,那就没什么意义了。不管怎么说,这都是关于您将读取CSS的代码放置在何处的时间安排。@vsync在呈现页面之前,如何运行
getComputedStyle
?如果您在浏览器中的任何时候运行
getComputedStyle
,都会影响性能。如果视图是数据驱动的,则数据应该位于单独的JSON文件中。SASS是在渲染之前编译的,因此可以在SPA页面中添加类似的内容。@RayShan-在SPA页面中,您可以在渲染任何内容之前运行任何javascript,因此您基本上有一个空白页面,因此重新绘制不是问题。这不是一个问题,除非它发生在一个很快的时间间隔(如w
if (window.getComputedStyle) {
  var mq = window.getComputedStyle(document.body,':after').getPropertyValue('content');
}

if (mq.indexOf('small') !== -1) {
  // do something
}
["0", "300px", "500px", "700px", "900px", "1100px"]
sass_options = { :custom => {'breakpoint_file' => 'breakpoints.json'} }

# This creates a SASS function debug() that returns $debug into SASS
module Sass::Script::Functions
  def breakpoints

    # Reading an array of breakpoints into a file
    unless breakpoints_array_raw = JSON.load( IO.read( options[:custom]['breakpoint_file'] ))
      raise Sass::SyntaxError.new("Error: Breakpoints file '#{options[:custom]['breakpoint_file']}' does not exist.")
    end

    # Converting strings in the array to SASS String literals
    breakpoints_array_sassy = breakpoints_array_raw.map { |s| Sass::Script::String.new(s) }

    # Returning the list into SASS
    Sass::Script::List.new( breakpoints_array_sassy, :space )
  end
end
$breakpoints: breakpoints()
var
  breakpoints = [],
  requestBreakpoints = $.get('breakpoints.json');

requestBreakpoints.done(function (response, textStatus, jqXHR){
    breakpoints = response; // You might want to remove "px" here
});
module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
      watch: {
          css: {
              files: ['sass/*.scss', 'sass/lib/*.scss', 'rosetta/*.rose'],
              tasks: ['rosetta', 'compass']
          }
      },
      compass: {
          dist: {
              options: {
                  sassDir: 'sass',
                  cssDir: '../static/css',
                  imagesDir: '../static/img',
                  javascriptsDir: '../static/js'
              }
          }
      },
      rosetta: {
          default: {
             src: ['rosetta/*.rose'],
             options: {
                 jsFormat: 'requirejs',
                 cssFormat: 'scss',
                 jsOut: '../static/js/lib/rosetta.js',
                 cssOut: 'sass/_shared_variables.scss'
             }
          }
      }
  });

  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-compass');
  grunt.loadNpmTasks('rosetta');
  grunt.registerTask('default', ['watch']);

};
{
  "name": "",
  "version": "0.0.0",
  "description": "",
  "main": "Gruntfile.js",
  "dependencies": {
    "grunt": "^0.4.5",
    "grunt-cli": "^0.1.13",
    "grunt-contrib-compass": "^0.9.1",
    "grunt-contrib-watch": "^0.6.1",
    "rosetta": "git+https://github.com/ukolka/rosetta.git"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}
...
$colors : ([COLORS])
...
var appColors = {[COLORS]};
var gulp    = require('gulp'),
    gutil   = require('gulp-util'),
    replace = require('gulp-replace');

var appColors = {
   "red"   : "#d63737",
   "green" : "#69c962"
};

gulp.task('scssVars', ()=>{
    var colorsString = JSON.stringify(appColors);
    colorsString  = colorsString.slice(2,colorsString.length - 2);

    return gulp.src('css/variables_template.scss')
        .pipe(replace(/[COLORS]/g, colorsString ))
        .pipe(rename('variables.scss'))
        .pipe(gulp.dest('/'))
});

// do more of less the same for your app.js, only without renaming, if possible